PHP Math
For everyday calculations on numbers, PHP offers a collection of built-in math functions.
PHP pi() Function
Calling pi() gives you the value of PI, ready to use in a formula.
Get the value of PI
Print the number that pi() gives back:
Output: PHP script
<?php
echo(pi());
?>
PHP min() and max() Functions
Pass several arguments to min() to get the smallest one, or to max() to get the largest.
Find min and max values
From the same four numbers, min() picks -200 and max() picks 150. The two results are printed side by side, with nothing between them:
Output: PHP script
<?php
echo(min(0, 150, -8, -200));
echo(max(0, 150, -8, -200));
?>
PHP abs() Function
abs() gives the absolute value of a number, which is its positive form.
Get absolute value
Here -6.7 becomes 6.7:
Output: PHP script
<?php
echo(abs(-6.7));
?>
PHP sqrt() Function
To get the square root of a number, call sqrt().
Get square root
8 times 8 is 64, so the square root of 64 is 8:
Output: PHP script
<?php
echo(sqrt(64));
?>
PHP round() Function
round() takes a floating-point number and gives you the closest integer.
Round numbers
3.60 rounds up to 4 and 0.49 rounds down to 0, printed with nothing between them as 40:
Output: PHP script
<?php
echo(round(3.60));
echo(round(0.49));
?>
Random Numbers
For a random number, call rand().
With no arguments you have no say in the range. The optional min and max parameters let you set the lowest and highest integers it may return.
So rand(10, 100) gives you an integer from 10 to 100, and both of those values can come up.
Generate a random number
With no arguments, the result changes from run to run:
Output: PHP script
<?php
echo(rand());
?>
Random number with min and max
Here the result is always an integer from 10 to 100:
Output: PHP script
<?php
echo(rand(10, 100));
?>