PHP Math

PHP includes many built-in math functions such as round, sqrt, abs and pow.

Syntaxround($number, $precision);

PHP has a rich set of math functions.

FunctionReturns
abs()Absolute value
round()Rounded number
ceil() / floor()Round up / down
sqrt()Square root
pow()Power
max() / min()Highest / lowest value

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Calculate the hypotenuse of a right triangle using sqrt() and pow() in a geometry tool.
  • Use abs() to display the absolute difference between a budget and actual spend.
  • Round a tax rate multiplication to two decimal places with round() before adding to an invoice.

More examples

round, ceil and floor

round() follows normal rounding rules; ceil() always rounds up and floor() always rounds down.

Example · php
<?php
$price = 19.567;

echo round($price, 2); // 19.57
echo ceil($price);     // 20
echo floor($price);    // 19

abs, pow and sqrt

pow() raises a number to a power and sqrt() computes the square root, together implementing the Pythagorean theorem.

Example · php
<?php
$a = 3;
$b = 4;
$hypotenuse = sqrt(pow($a, 2) + pow($b, 2));

echo abs(-42);       // 42
echo $hypotenuse;    // 5

min, max and fmod

min() and max() work on arrays or individual arguments; fmod() handles the modulo of floating-point numbers.

Example · php
<?php
$scores = [88, 45, 97, 62, 73];

echo min($scores); // 45
echo max($scores); // 97
echo fmod(10, 3);  // 1 (float modulo)

Discussion

  • Be the first to comment on this lesson.