PHP has a set of built-in math functions that allow you to perform mathematical tasks on numbers. Whether you need to generate a random number or find the square root of a value, PHP makes it simple.
pi() FunctionThe pi() function returns the value of PI.
<?php
echo pi(); // Output: 3.1415926535898
?>
min() and max()These functions find the lowest or highest value in a list of arguments.
<?php
echo min(0, 150, 30, 20, -8, -200); // Output: -200
echo max(0, 150, 30, 20, -8, -200); // Output: 150
?>
abs() - Absolute ValueReturns the absolute (positive) value of a number.
<?php
echo abs(-6.7); // Output: 6.7
?>
sqrt() - Square RootReturns the square root of a number.
<?php
echo sqrt(64); // Output: 8
?>
round() - RoundingThe round() function rounds a floating-point number to its nearest integer.
<?php
echo round(0.60); // Output: 1
echo round(0.49); // Output: 0
?>
rand() - Random NumbersThe rand() function generates a random number. You can specify the range of the random number too.
<?php
echo rand(); // Returns a random number
echo rand(10, 100); // Returns a random number between 10 and 100
?>
rand() function is not cryptographically secure. For security purposes (like passwords), use random_int() instead.
ceil() to always round up to the nearest integer, and floor() to always round down.
| Function | Description |
|---|---|
pi() | Returns 3.14... |
min() / max() | Returns the lower / higher value. |
abs() | Returns the positive value. |
sqrt() | Returns the square root. |
round() | Rounds to the nearest whole number. |
rand() | Generates a random number. |