How To Work with Numbers in PHP

The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

Introduction

Numbers are extremely common in programming. They are used to represent things like screen size dimensions, geographic locations, money, points, the amount of time that passes in a video, positions of game avatars, and colors through assigning numeric codes.

Being able to effectively perform mathematical operations in programming is an important skill to develop because of how frequently you’ll be working with numbers. Though a high-level understanding of mathematics can certainly help you become a better programmer, it is not a prerequisite. If you don’t have a background in mathematics, try to think of math as a tool to accomplish what you would like to achieve, and as a way to improve your logical thinking.

We’ll be working with the two numeric data types in PHP, integers and floats:

  • Integers are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …).
  • Floating point numbers, or floats, are real numbers that contain a decimal point (as in 9.0 or -2.25).

This tutorial will go over many different operators that can be used with numerical data types in PHP, as well as how PHP handles “type juggling” and built-in math functions.

Operators

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). Operators are used for basic decision making, such as instructing a program to perform an action based on a value.

Assignment Operator

The most basic operator is the assignment operator, a single equals sign: =. This assignment operator is used when setting the value for a variable. A variable is like a box. Many different things may be stored in a box. Additional items may be added to the box. The items in the box can be rearranged or each given a sticker. The box may also be emptied and something new can be added to the box. This is exactly what happens when a variable is used in code. The variable is given a name, and that named variable is assigned a value:

$box=3;
var_dump($box);
$box="Hello";
var_dump($box);

To see the variable type along with the value, the var_dump() function is used instead of echo. The variable named $box is assigned an int with a value of 3. Then that same $box variable is assigned a new value of "Hello". This is the same as emptying the box and adding something new. Now when the var_dump() function is called, we get entirely different information about the value of the $box variable:

Output
int(3) string(5) "Hello"

After the first assignment, the $box variable contains the integer value of 3. After the second assignment, the $box variable contains a string of 5 characters matching “Hello”.

To make our $box more useful, let’s take a look at our next type of operator.

Arithmetic Operators

PHP has arithmetic operators that work the same in a computer program as they do on a calculator, or even pen and paper. The important aspect to pay attention to is the symbol used for the operation. Let’s take a look at the most common arithmetic operators.

Addition (+): Start with the first value and add the next value to that number. This can performed using either a numerical value itself or the variable that contains the value:

$start=10;
var_dump($start+3);

The result is the sum of this equation:

Output
int(13)

Subtraction (-): Start with the first value and subtract, or remove, the next value from the previous value:

$start=10;
var_dump($start-3);

The result is the difference of this equation:

Output
int(7)

Multiplication (*): Start with the first value and multiply it with the next value:

$start=10;
var_dump($start*3);

This is the same as adding the first number as many times as the second number:

$start=10;
var_dump($start+$start+$start);

Both of which give us the same result, the product of the equation:

Output
int(30)

Division (/): How many times can the second value go into the first value:

$start=10;
var_dump($start/3);

The result is the quotient of this equation:

Output
float(3.3333333333333)

In this case the result is given as a float instead of an integer because 3 does not go into 10 evenly. We can tell PHP to give us the result as just the integer value by adding (int), which will ignore anything after the .:

$start=10;
var_dump((int) $start/3);

Giving the results as an integer, which is a whole number:

Output
int(3)

When the leftover value, or remainder, of a division equation is desired, that is called the modulo (%):

$start=10;
var_dump($start%3);
var_dump(3%$start);

The first var_dump gives us the remainder of the previous division equation. When the equation is reversed, the modulo returns 3 because 10 goes into 3 zero times, leaving the original 3 as the remainder:

Output
int(1) int(3)

The modulo is often used when creating a pattern based on odd or even rows. When determining whether an integer count of a row is odd or even, use %2:

var_dump(10%2);
var_dump(11%2);

An even integer will always give a result of 0, because even numbers are divisible by 2, while an odd integer will always give the result of 1 because it is not evenly divisible:

Output
int(0) int(1)

PHP is able to perform complex calculations quickly and provides many more tools to write whichever calculations are needed. Exponents, percentage, square root, and many more operations are possible. Before we take a look at some of these mathematical functions, let’s explore another type of operator, which combines the assignment and arithmetic operators.

Arithmetic Assignment Operators

Say there is a basket with 10 apples. To represent this in code we could write $basket = 10. Next we pick an additional 5 apples and place them in the basket. Instead of using the integer 10, we can use the value of 10 that is stored in the $basket variable: $basket = $basket + 5. While this is technically correct, it is rather redundant. We just want to add 5 more apples to the existing basket. That’s where arithmetic assignment operators come in. Instead of repeating the variable, we can write $basket += 5. This works exactly like the previous expression; it tells the code to:

  1. Take the value of $basket
  2. Add 5 to that value
  3. Reassign the new value to $basket

You can use this same principle with other arithmetic operators:

Expression Result (assuming $i = 10)
$i += 5 Add 10 + 5; Result: $i = 15
$i -= 5 Subtract 10 – 5; Result: $i = 5
$i *= 5 Multiply 10 * 5; Result: $i = 50
$i /= 5 Divide 10 / 5; Result: $i = 2

If Sammy decides to chomp on some of the apples in our basket, we could use something like $basket -= 6, which would leave us with the integer 9 assigned to $basket. So far, the program looks something like this:

$basket = 10;
$basket += 5;
$basket -= 6;
echo $basket;

When $basket is echoed in the final line, it gives the final value:

Output
9

While Sammy may be able to eat many apples at once, I can only eat a single apple at a time.

Increment Operator

For increasing a number by 1, PHP provides a separate increment operator, which is a double plus sign (++). This can be use to increment a variable independently (on its own line) or directly in an expression. Let’s go back to the apple basket example where the current value of the $basket variable is 9:

++$basket;
echo $basket;

The first line adds 1 to the current value, which was 9, and the next line gives the result:

Output
10

We can do the same thing in a single line:

echo ++$basket;

First it adds 1 to the current value, which was 10, and the next line gives the result:

Output
11

When the value of $basket is output once more:

echo $basket;

It confirms that the $basket variable was actually updated in the previous line, not just added to the output result:

Output
11

In each of the previous lines, the increment operator was used before the variable. This pre-incremented action is applied to the variable before any other action, such as the echo command. Using ++$basket is the same as writing $basket += 1. The increment operator can also be used after the variable as a post-increment. When the variable is set independently, the order doesn’t matter, but when it is used within an expression, the order becomes important. Let’s repeat those same lines, only this time putting the increment operator after the variable:

$basket++;
echo $basket;

The first line adds 1 to the current value, which was 11, and the next line gives the result. This works exactly the same as the pre-increment lines in the previous example:

Output
12

Now we get to the difference with a post-incremented value:

echo $basket++;

The echo action happens before the value is incremented, so the result of the second echo still shows the value of $basket before it was increase by 1:

Output
12

A final echo command confirms that the variable was actually incremented after the echo was processed:

echo $basket;

Showing that the final value of $basket:

Output
13

Along with the increment operator, PHP give us the ability to decrease a value by 1 using the decrement operator.

Decrement Operator

To decrease a value by 1, we can use the decrement operator, which is a double minus sign (--). As with the increment operator, this operator can be added before or after the variable, but position may affect the output of the program:

echo --$basket; # Pre-decrement
echo $basket--; # Post-decrement
echo $basket;

The first line removes 1 from the current value, which was 13, before the echo command is executed. The next line executes the echo command before the post-decrement operator is evaluated, leaving the output the same. Once again, the final echo demonstrates that the value of $basket was actually decremented in the previous line, giving us a decreased value:

Output
12 12 11

Keep this order of the operator in mind as we take a look at how operator precedence can play an important role in our results.

Operator Precedence

The precedence of an operator specifies how “tightly” it binds two expressions together. This is often referred to as the “order of operations.” This means that different operators are given greater importance and are applied first. When evaluating a mathematical equation, multiplication and division are always performed before addition and subtraction. For example:

echo 1 + 5 * 3;

In this expression, the multiplication (*) operator has a higher precedence than the addition (+) operator and is therefore evaluated first: 5 * 3 = 15. The addition is then performed as 1 + 15 = 16. This provides an end result of 16:

Output
16

If the order of operations was not followed, 1 + 5 would be evaluated first and then that result would have the multiplication applied, giving us 6 * 3 = 18.

The increment and decrement operators cannot be applied to a number; they are used with variables. We can, however, add variables to an equation in which we increment or decrement that value. When these incremented or decremented variables are used, the equation is either performed before or after the increment or decrement operation:

$my_num = 8;
echo 7 + $my_num++ + 9;
echo $my_num;
echo 7 + --$my_num + 9;
echo $my_num;

In the first echo line, the mathematical expression is performed using the original value of $my_num before the post-increment operator increases the value. It’s as if we had written echo 7 + 8 + 9;, which gives us the result of 24. We see from the second echo that $my_num is now set to 9. The second mathematical equation is performed after the pre-decrement operation, which means that the value of $my_num is now set to 8, and the mathematical equation itself is the same. After the mathematical equation is executed, the post-decrement operator is executed, giving the final result of the $my_num variable:

Output
24 9 24 8

Grouping Operations

Parentheses always have the highest level of precedence, providing a way to group operations or force precedence. For example, adding parenthesis to the previous equation:

echo (1 + 5) * 3;

Because the items within the parenthesis are evaluated before the multiplication, the result is different:

Output
18

To summarize the Operator Precedence of Mathematical Equations:

  1. Parentheses are evaluated from left to right.
  2. Multiplication and division are evaluated from left to right.
  3. The final result is evaluated using any addition and subtraction from left to right.

Type Juggling

PHP does not define a variable type when a variable is declared or set. Instead, a variable’s type is determined by the context in which the variable is used. We can use var_dump() to show the details of a variable, including its type:

$my_var = 'string';
var_dump($my_var);
$my_var = 1;
var_dump($my_var);

When a string value is assigned to a variable, that variable becomes a string. If an integer value is then assigned to that same variable, it becomes an integer:

Output
string(6) "string" int(1)

PHP will also set the type based on the evaluation of an equation:

$var1 = 1.2;
$var2 = 2;
$var3 = 12;
var_dump($var1 * $var2);
var_dump($var3 * $var2);
var_dump($var1, $var2, $var3);

If either operand is a float, then both operands are evaluated as floats, and the result will be a float, as show with the first var_dump. Otherwise, the operands will be interpreted as integers, and the result will also be an integer, as shown with the second var_dump:

Output
float(2.4) int(24) float(1.2) int(2) int(12)

From the third var_dump we see that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and the resulting type of the expression itself.

Other data types such as strings and Booleans may also be converted to a number. This can cause much confusion, so it is best avoided. Although PHP will produce a notice or warning, it will still do its best to “juggle” the variables into a type that can be evaluated. For example:

Expression Result Type Juggling
2 * false 0 the boolean is converted to the integer 0
2 * true 2 the boolean is converted to the integer 1
2 * 'hi' 0 the string is converted to the integer 0
2 * '1' 2 the string is converted to the integer 1

While the loose typing of PHP can make it faster and easier to write code, it often makes it more difficult to track down problems. Be conscious of the variable types used in an application.

Math Functions

A function is a block of statements that can be used repeatedly in a program. PHP comes with many built-in functions that allow us to preform additional math calculations.

When working with both positive and negative numbers, you can get the absolute value of the number with the abs function:

echo abs(-1.3);

This ignores the + or - before a number and just returns the number itself:

Output
1.3

There are multiple options when estimating with numbers or retrieving the integer value of a float:

echo round(1.3);
echo round(1.5);
echo ceil(1.3);
echo floor(1.5);

The round function will return the closest whole number, with .5 evaluating to the higher number. The ceil function will always round up, while the floor function will always round down:

Output
1 2 2 1

The ratio of any circle is the same. Because this it true, the circumference of any circle can be determined by multiplying its diameter by a special number known as pi (Π):

echo pi();
echo 4 * pi();

The pi function in PHP returns the first 14 digits of pi, since pi is an irrational number, meaning that its decimal form never ends. This function can be used to calculate circumference of a circle with a diameter of 4:

Output
3.1415926535898 12.566370614359

Whether it’s flipping a coin or rolling a die, when the goal for a result is up to chance, random numbers provide the tool. PHP provides the rand function to return this unpredictable, random result:

echo rand();

This function will display a number between 0 and the getrandmax configured on the machine. When you need a little less randomness, or want to increase the max number, you may specify the min and max inclusively. To return a random three-digit number:

var_dump(rand(100, 999));

Each time this rand function is called, it will return a three-digit number between 100 and 999.

The calculation to return a random number is not actually random, so when it comes to security and cryptography, PHP provides more cryptographically secure functions. To generate a cryptographic random integer that is suitable for unbiased results such as shuffling cards or drawing a winning number, use the random_int function:

var_dump(random_int(-999, 999));

With random_int you must specify the inclusive min and max numbers. Both rand and rand_int accept negative numbers.

When generating cryptographically secure values for salts, keys, or initialization vectors that can take a byte string, use random_bytes with the specified string length:

var_dump(random_bytes(20));

You will get a new random byte string each time, which will look something like:

Output
string(20) "q8?Ud;??W?p4?C????"

There are many more built-in math functions for PHP. Check out the php.net documentation to learn more.

Conclusion

This tutorial covered many of the operators you’ll use when working with the integer and float numeric data types. It also demonstrated how the precedence and position of operators can affect the outcome. These outcomes brought us to the way PHP “juggles” variable types and the issues that can cause. Finally a brief introduction to built-in functions expanded the mathematical choices available to an application. To learn more about other data types, take a look at Understanding Data Types in PHP.

Originally posted on DigitalOcean Community Tutorials
Author: alenaholligan

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *