Learn

Short lessons with real code you can edit and run on the page.

Numbers and Math in PHP

Lesson 6 PHP 8.5 Runs in your browser
In short

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 / 4 gives float(2.5), but 10 / 2 gives int(5), since those two ints divide evenly.
  • The result of % has the sign of the number on its left, so -10 % 3 is -1.
  • With default settings, echo 0.1 + 0.2 prints 0.3, but var_dump(0.1 + 0.2) shows float(0.30000000000000004).
  • round(-2.5) gives float(-3), because round() moves a half away from zero by default and always returns a float.
  • Dividing by zero with /, % or intdiv() 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).

PHP arithmetic operators
OperatorNameExampleResult
+Addition17 + 522
-Subtraction17 - 512
*Multiplication17 * 585
/Division17 / 53.4
%Modulo (remainder)17 % 52
**Exponentiation17 ** 2289

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.

PHP
<?php
$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";
Output
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.

PHP
<?php
echo 2 + 3 * 4, "\n";
echo (2 + 3) * 4, "\n";
echo -2 ** 2, "\n";
Output
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.

PHP
<?php
var_dump(10 / 2);
var_dump(10 / 4);
var_dump(10.0 / 2);
var_dump(intdiv(10, 4));
Output
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.

PHP
<?php
$minutes = 135;
echo intdiv($minutes, 60), " hours and ", $minutes % 60, " minutes";
Output
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.

PHP
<?php
var_dump(10 % 3);
var_dump(-10 % 3);
var_dump(10 % -3);
var_dump(fmod(7.5, 2));
Output
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.

PHP
<?php
$total = 100;
$people = 0;
echo $total / $people;
Output

Fatal error: Uncaught DivisionByZeroError: Division by zero in /app/main.php:4
Stack trace:
#0 {main}
  thrown in /app/main.php on line 4

The 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.

PHP
<?php
echo 0.1 + 0.2, "\n";
var_dump(0.1 + 0.2);
var_dump(0.1 + 0.2 == 0.3);
Output
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.

PHP
<?php
var_dump(round(0.1 + 0.2, 2) == 0.3);
var_dump(abs(0.1 + 0.2 - 0.3) < 0.00001);
Output
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.

PHP
<?php
echo 10 / 3, "\n";
var_dump(10 / 3);
Output
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.

PHP
<?php
var_dump(round(2.5));
var_dump(round(-2.5));
var_dump(round(3.14159, 2));
var_dump(round(1234.5678, -2));
Output
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.

PHP
<?php
var_dump(floor(4.7));
var_dump(floor(-4.7));
var_dump(ceil(4.2));
var_dump(ceil(-4.2));
Output
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.

PHP rounding functions compared
FunctionRounds9 / 2 (4.5)-9 / 2 (-4.5)
round()To the nearest whole number, halves away from zerofloat(5)float(-5)
floor()Downfloat(4)float(-5)
ceil()Upfloat(5)float(-4)
(int) castToward zeroint(4)int(-4)
intdiv()Toward zeroint(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.

PHP
<?php
var_dump(round(2.5, 0, RoundingMode::HalfEven));
var_dump(round(19.99, 2, RoundingMode::NegativeInfinity));
var_dump(floor(19.99 * 100) / 100);
Output
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.

PHP
<?php
$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";
Output
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.

PHP
<?php
var_dump(PHP_INT_MAX + 1);
var_dump(PHP_INT_MAX + 1 == PHP_INT_MAX + 2);
Output
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.

PHP
<?php
$i = 5;
echo $i++, "\n";
echo $i, "\n";
echo ++$i, "\n";
Output
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.

PHP
<?php
$score = 10;
$score += 5;
$score *= 2;
echo $score;
Output
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.

PHP
<?php
$letter = "a";
$letter++;
echo $letter, "\n";
echo str_increment("Az");
Output

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.50 from number_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. Use fmod() 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) * 10 is stored as 7.999999999999999, and floor() and (int) both cut it to 7. Call round() 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.

PHP
<?php
$price = number_format(1234.5, 2);
echo $price + 1;
Output

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.

PHP
<?php
$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";
Output
Show the solution
<?php
$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.

  1. 1What does this script print?

    <?php
    echo 7 / 2;
  2. 2What does this script print?

    <?php
    echo -7 % 3;
  3. 3What does this script print?

    <?php
    echo round(-2.5);
  4. 4Which PHP call returns the string 1,234.50?

  5. 5What does this script print?

    <?php
    $i = 5;
    echo $i++;

Frequently asked questions

How do you round to 2 decimal places in PHP?
Call round($number, 2) to round a number to 2 decimal places. It returns a float, so echo round(3.10, 2) prints 3.1 without the trailing zero. To always show two decimals, as with prices, use number_format(), as in number_format(3.10, 2), which returns the string 3.10.
How do you round down to 2 decimal places in PHP?
On PHP 8.4 and later, call round($number, 2, RoundingMode::NegativeInfinity). It keeps 19.99 as 19.99, while the older floor($number * 100) / 100 returns 19.98, because 19.99 * 100 is stored as 1998.9999999999998. To round down to a whole number, floor() works on any PHP version.
How do you round up in PHP?
Use ceil() to round a number up to a whole number. It returns a float, such as float(5) for ceil(4.2), and (int) ceil(4.2) gives the int 5. On PHP 8.4 and later, round($number, 2, RoundingMode::PositiveInfinity) rounds up at two decimal places.
How do you do integer division in PHP?
Use intdiv() to divide two integers and get a whole-number result. intdiv(17, 5) returns 3 and drops the remainder, which 17 % 5 returns as 2. The / operator would return the float 3.4 instead.
What is the difference between $i++ and ++$i in PHP?
Post-increment, $i++, returns the value of $i from before the increment. Pre-increment, ++$i, adds 1 first and returns the new value. If $i is 5, echo $i++ prints 5 and echo ++$i prints 6, and either way $i ends up as 6.
What math functions does PHP have?
PHP has built-in math functions such as abs(), sqrt(), pow(), max() and min(). abs() drops the minus sign, sqrt() returns a square root, pow() raises a number to a power, and max() and min() return the largest and smallest value. PHP 8.6 adds clamp(), which keeps a number between a minimum and a maximum.
How do you generate a random number in PHP?
Call random_int() with a minimum and a maximum, such as random_int(1, 6) for a dice roll. Both limits are included, and each call makes a new random pick. Unlike rand() and mt_rand(), random_int() is safe for security uses such as tokens.