Skip to main content

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:

Prompt
Write a PHP script that outputs the value of PI using the pi() function.
Output: PHP script

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:

Prompt
Write a PHP script that finds the lowest and highest values in a list of numbers (0, 150, -8, -200) using min() and max().
Output: PHP script

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:

Prompt
Write a PHP script that returns the absolute value of -6.7 using the abs() function.
Output: PHP script

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:

Prompt
Write a PHP script that returns the square root of 64 using the sqrt() function.
Output: PHP script

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:

Prompt
Write a PHP script that rounds the values 3.60 and 0.49 using the round() function.
Output: PHP script

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:

Prompt
Write a PHP script that generates a random number using the rand() function.
Output: PHP script

Random number with min and max

Here the result is always an integer from 10 to 100:

Prompt
Write a PHP script that generates a random integer between 10 and 100 using rand(10, 100).
Output: PHP script