Numbers and Math in PHP
PHP does math with the arithmetic operators +, -, *, /, % and **. Division returns a float unless both numbers are integers that divide evenly. round(), floor() and ceil() round the results, and number_format() formats them for display.
Key facts
10 / 4givesfloat(2.5), but10 / 2givesint(5), since those two ints divide evenly.- The result of
%has the sign of the number on its left, so-10 % 3is-1. - With default settings,
echo 0.1 + 0.2prints0.3, butvar_dump(0.1 + 0.2)showsfloat(0.30000000000000004). round(-2.5)givesfloat(-3), becauseround()moves a half away from zero by default and always returns a float.- Dividing by zero with
/,%orintdiv()throws a DivisionByZeroError, which stops the script if nothing catches it.
What are the arithmetic operators in PHP?
PHP's arithmetic operators are +, -, *, /, % and **. They add, subtract, multiply, divide, find the remainder (modulo, also called modulus) and raise a number to a power. They work on both of PHP's number types, integers (int) and floating-point numbers (float).
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 17 + 5 | 22 |
- | Subtraction | 17 - 5 | 12 |
* | Multiplication | 17 * 5 | 85 |
/ | Division | 17 / 5 | 3.4 |
% | Modulo (remainder) | 17 % 5 | 2 |
** | Exponentiation | 17 ** 2 | 289 |
A minus sign in front of a single value, as in -$a, flips its sign. This script stores 17 and 5 in two variables and uses each operator once.
$a = 17;
$b = 5;
echo $a + $b, "\n";
echo $a - $b, "\n";
echo $a * $b, "\n";
echo $a / $b, "\n";
echo $a % $b, "\n";
echo $a ** 2, "\n";22 12 85 3.4 2 289
Only the division prints a decimal, because 17 doesn't divide evenly by 5. The last line raises 17 to the power of 2.
In what order does PHP do arithmetic?
PHP does ** first, then *, / and %, then + and -. Operators of equal rank run left to right, which makes 10 - 4 - 3 equal to (10 - 4) - 3, or 3. The exception is **, which runs right to left and turns 2 ** 3 ** 2 into 2 ** 9, or 512.
Parentheses change the order, and the operator precedence table on php.net lists every operator.
echo 2 + 3 * 4, "\n";
echo (2 + 3) * 4, "\n";
echo -2 ** 2, "\n";14 20 -4
The last line prints -4, not 4. Because ** ranks above the minus sign, PHP reads -2 ** 2 as -(2 ** 2). Write (-2) ** 2 to square a negative number.
When does division return a float in PHP?
The / operator gives an int only when both numbers are ints and nothing is left over. A float on either side gives a float, even when the answer is a whole number.
var_dump(10 / 2);
var_dump(10 / 4);
var_dump(10.0 / 2);
var_dump(intdiv(10, 4));int(5) float(2.5) float(5) int(2)
var_dump() prints each value with its type, which echo leaves out. Both 10 / 2 and 10.0 / 2 print 5 with echo, but var_dump() tells them apart as int(5) and float(5).
For integer division, use intdiv(), since PHP has no operator for it. intdiv(10, 4) returns int(2) and drops the remainder. It cuts toward zero, so intdiv(-7, 2) is -3, while floor(), which always rounds down, turns -7 / 2 into -4.
Pair intdiv() with % to split a total into whole units and a remainder. This script turns 135 minutes into hours and minutes.
$minutes = 135;
echo intdiv($minutes, 60), " hours and ", $minutes % 60, " minutes";2 hours and 15 minutes
How does the modulo operator work in PHP?
The modulo operator % returns the remainder after dividing one int by another. 17 % 5 is 2, because 5 fits into 17 three times with 2 left over. The result has the same sign as the number on the left, whatever the sign of the number on the right.
var_dump(10 % 3);
var_dump(-10 % 3);
var_dump(10 % -3);
var_dump(fmod(7.5, 2));int(1) int(-1) int(1) float(1.5)
Because PHP converts both numbers to ints before it takes the remainder, % never returns a decimal. For floats, call fmod(), which gives float(1.5) as the remainder of 7.5 divided by 2.
A remainder of 0 means one number divides evenly by the other. That's how code tells even numbers from odd ones, since $n % 2 is 0 for every even number and 1 or -1 for an odd one.
What happens when you divide by zero in PHP?
Dividing by zero throws a DivisionByZeroError, which stops the script. The same error comes from /, % and intdiv(), though for % its message reads Modulo by zero.
$total = 100;
$people = 0;
echo $total / $people;
Fatal error: Uncaught DivisionByZeroError: Division by zero in /app/main.php:4
Stack trace:
#0 {main}
thrown in /app/main.php on line 4The script stops at line 4, and no code after that line would run. PHP throws DivisionByZeroError as an Error, a kind of problem that code can still catch with try and catch, which a later lesson covers.
Before PHP 8.0, / by zero printed a warning and kept going, so older tutorials may show that. A PHP 8.0 change proposal, the engine warnings RFC, made it an error. The fdiv() function divides by zero without an error and returns INF, -INF or NAN, the float values for infinity and not a number.
Why doesn't 0.1 + 0.2 equal 0.3 in PHP?
PHP stores floats as binary fractions, which can't hold 0.1 or 0.2 exactly. Each one is off by a tiny amount, so their sum lands a little above 0.3. A float result can be off in its last digits.
echo 0.1 + 0.2, "\n";
var_dump(0.1 + 0.2);
var_dump(0.1 + 0.2 == 0.3);0.3 float(0.30000000000000004) bool(false)
echo rounds the result for display and prints 0.3. var_dump() prints enough digits to show that the stored value isn't 0.3. The == operator compares the stored values, so it gives false.
Round a float result before you compare it, or check that the gap between the two values is tiny. abs() returns a number without its minus sign. The test abs($a - $b) < 0.00001 asks whether two floats are less than 0.00001 apart.
var_dump(round(0.1 + 0.2, 2) == 0.3);
var_dump(abs(0.1 + 0.2 - 0.3) < 0.00001);bool(true) bool(true)
Why do echo and var_dump() show floats differently in PHP?
echo and var_dump() follow two different php.ini settings. echo uses precision, which is 14 significant digits by default. Since PHP 8.0, var_dump() uses serialize_precision, whose default of -1 prints the fewest digits that still read back as exactly the same float.
echo 10 / 3, "\n";
var_dump(10 / 3);3.3333333333333 float(3.3333333333333335)
The 14 applies when echo prints a float and when a float is joined into a string. It doesn't change the stored value, which var_dump() shows has more digits. Both settings can be changed in php.ini, so the same echo can print more digits on another server.
How do you round numbers in PHP?
Call round() to round a number to the nearest whole number or to a set number of decimals. By default, a half goes away from zero, which turns 2.5 into 3 and -2.5 into -3.
The second argument, the value after the comma, sets how many decimals to keep, and a negative one rounds to tens, hundreds and so on.
var_dump(round(2.5));
var_dump(round(-2.5));
var_dump(round(3.14159, 2));
var_dump(round(1234.5678, -2));float(3) float(-3) float(3.14) float(1200)
round() always returns a float, even for a whole number such as float(3). echo leaves out the decimal point when it prints that float, and echo round(2.5) shows 3.
floor() rounds down and ceil() rounds up, both to a whole number. Down means toward negative infinity, which makes floor(-4.7) -5, not -4. Both functions return floats too.
var_dump(floor(4.7));
var_dump(floor(-4.7));
var_dump(ceil(4.2));
var_dump(ceil(-4.2));float(4) float(-5) float(5) float(-4)
Use ceil() to count how many pages a list needs. A list of 23 items at 10 per page needs ceil(23 / 10) pages, which is 3, and our PHP pagination tutorial works out its page count with ceil() as well.
What is the difference between round(), floor() and ceil() in PHP?
round(), floor() and ceil() each round in a different direction. This table compares them with intdiv() and the (int) cast on 9 / 2 and -9 / 2, which are 4.5 and -4.5.
| Function | Rounds | 9 / 2 (4.5) | -9 / 2 (-4.5) |
|---|---|---|---|
round() | To the nearest whole number, halves away from zero | float(5) | float(-5) |
floor() | Down | float(4) | float(-5) |
ceil() | Up | float(5) | float(-4) |
(int) cast | Toward zero | int(4) | int(-4) |
intdiv() | Toward zero | int(4) | int(-4) |
Use round() for the closest value, such as an average or a price. Use floor() to count complete groups, such as full boxes, ceil() to count the groups you need, such as pages, and intdiv() when the result should stay an int.
What changed in round() in PHP 8.4?
PHP 8.4 added the RoundingMode enum and four new ways to round. An enum is a fixed set of named values, and you pass one as the third argument of round(), written as RoundingMode:: plus its name.
The new modes are PositiveInfinity, NegativeInfinity, TowardsZero and AwayFromZero. The four older modes, which only decide which way a half goes, got enum names too, such as HalfEven, and their constants, such as PHP_ROUND_HALF_EVEN, still work.
var_dump(round(2.5, 0, RoundingMode::HalfEven));
var_dump(round(19.99, 2, RoundingMode::NegativeInfinity));
var_dump(floor(19.99 * 100) / 100);float(2) float(19.99) float(19.98)
HalfEven sends a half to the even neighbor, so 2.5 rounds to 2. NegativeInfinity rounds 19.99 down at 2 decimals and keeps it as 19.99. The older trick floor(19.99 * 100) / 100 returns 19.98, because 19.99 * 100 is stored as 1998.9999999999998.
Some pages list constants such as PHP_ROUND_CEILING for the new modes, but PHP never shipped them. The new modes exist only in the enum.
How do you format a number with commas and decimals in PHP?
Call number_format() to add thousands separators and show a fixed number of decimals. It rounds halves away from zero, like round(), and returns a string that's ready to print. The third and fourth arguments set the decimal point and the thousands separator.
$n = 1234567.891;
echo number_format($n), "\n";
echo number_format($n, 2), "\n";
echo number_format($n, 2, ',', '.'), "\n";
echo number_format($n, 2, '.', ''), "\n";1,234,568 1,234,567.89 1.234.567,89 1234567.89
With no second argument, number_format() rounds to a whole number and leaves out the decimal point. Passing ',' and '.' swaps the two marks, and an empty string as the fourth argument drops the separators.
The result is a string, so do the math first and format the number last. Our invoice system tutorial prints each payment amount with number_format() and 2 decimals. The printf() and sprintf() functions format numbers too.
What happens when a number is too big for a PHP integer?
A result larger than PHP_INT_MAX, the largest int PHP can store, becomes a float. A float can't keep every digit of a number that big, so PHP_INT_MAX + 1 and PHP_INT_MAX + 2 come out as the same float.
var_dump(PHP_INT_MAX + 1);
var_dump(PHP_INT_MAX + 1 == PHP_INT_MAX + 2);float(9.223372036854776E+18) bool(true)
For exact math on numbers this big, PHP has the BCMath and GMP functions. Casting a float that big to an int prints the warning that Data Types in PHP describes, and there's no guarantee which int you get back.
How do ++ and -- work in PHP?
The ++ and -- operators add 1 to a variable or subtract 1 from it. Written before the variable, as ++$i (pre-increment), the operator changes it first and returns the new value. Written after it, as $i++ (post-increment), it returns the old value and then changes the variable.
$i = 5;
echo $i++, "\n";
echo $i, "\n";
echo ++$i, "\n";5 6 7
The first line prints 5 because $i++ hands back the old value, and $i is 6 straight after. Both operators work on floats as well, turning 1.5 into 2.5.
To change a variable by more than 1, use a combined assignment operator. $score += 5 is short for $score = $score + 5, and -=, *=, /=, %= and **= work the same way.
$score = 10;
$score += 5;
$score *= 2;
echo $score;30
What changed for ++ and -- in PHP 8.3 and 8.5?
PHP 8.3 and 8.5 added messages for ++ and -- on values that aren't numbers. Since 8.3, either operator on true or false, or -- on null, prints a warning that the operation has no effect.
Since 8.3, PHP also prints a deprecation notice for -- on a string that isn't a number. It does the same for ++ on an empty string or one with characters other than letters and digits, such as "a-b".
Since 8.5, ++ on any string that isn't a number, such as "a", prints a deprecation notice too.
$letter = "a";
$letter++;
echo $letter, "\n";
echo str_increment("Az");Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in /app/main.php on line 3 b Ba
The letter still moves on to b, but the notice points to str_increment(), added in PHP 8.3. It steps through letters without a notice, and str_increment("Az") returns "Ba".
Common mistakes with numbers in PHP
Most number mistakes in PHP don't stop the script. Read the output as well as any message, since a script can also finish with a wrong number and no message.
- Warning: A non-numeric value encountered. A string such as
1,234.50fromnumber_format()went into math, and PHP read it only up to the comma. Do the math on the number, then format it last. - Deprecated: Implicit conversion from float 7.5 to int loses precision. The
%operator got a float with a fraction and dropped the fraction before dividing. Usefmod()for the remainder of a float. - Parse error: syntax error, unexpected identifier. A minus sign copied from a document or web page can be an en dash, which looks like a minus but isn't one. Retype it, or paste the code into the PHP validator, which marks the line.
- floor() returns 7 instead of 8.
(0.1 + 0.7) * 10is stored as 7.999999999999999, andfloor()and(int)both cut it to 7. Callround()first when a float result should be a whole number.
This script formats the price before adding 1, so PHP prints the non-numeric warning. Change it so it adds 1 first and calls number_format() last.
$price = number_format(1234.5, 2);
echo $price + 1;Warning: A non-numeric value encountered in /app/main.php on line 3 2
Exercise
A $1,240.50 bill gets a 20% tip and is split between 5 people. Change the three echo lines so each amount goes through number_format() with two decimals. The program should print Tip: $248.10, Total: $1,488.60 and Each pays: $297.72 on three lines, the amounts the tip calculator gives.
$bill = 1240.50;
$tipPercent = 20;
$people = 5;
$tip = $bill * $tipPercent / 100;
$total = $bill + $tip;
$each = $total / $people;
echo "Tip: $" . $tip . "\n";
echo "Total: $" . $total . "\n";
echo "Each pays: $" . $each . "\n";
Tip: $248.10 Total: $1,488.60 Each pays: $297.72
Show the solution
$bill = 1240.50;
$tipPercent = 20;
$people = 5;
$tip = $bill * $tipPercent / 100;
$total = $bill + $tip;
$each = $total / $people;
echo "Tip: $" . number_format($tip, 2) . "\n";
echo "Total: $" . number_format($total, 2) . "\n";
echo "Each pays: $" . number_format($each, 2) . "\n";
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this script print?
echo 7 / 2;Since 7 doesn't divide evenly by 2, the / operator gives the float 3.5. PHP doesn't drop the decimals here, and intdiv(7, 2) is the call that would return 3.
-
2What does this script print?
echo -7 % 3;The remainder takes the sign of the number on the left, so -7 % 3 is -1. PHP doesn't turn a negative remainder into a positive one, which is why 2 is wrong here.
-
3What does this script print?
echo round(-2.5);By default, round() moves a half away from zero, so -2.5 becomes -3. Getting -2 would take a different rounding mode, such as RoundingMode::HalfEven, as the third argument.
-
4Which PHP call returns the string 1,234.50?
number_format() with 2 decimals adds the comma and keeps the trailing zero. round(1234.5, 2) returns the float 1234.5, which echo prints with no comma and no trailing zero, and the version with ',' and '.' returns 1.234,50.
-
5What does this script print?
$i = 5; echo $i++;Post-increment returns the value from before the change. The echo prints 5, and $i becomes 6 afterward. Writing ++$i instead would print 6.























