PHP Math

PHP pi() Function

The pi() function returns value of the PI:

echo(pi()); // returns value is 3.1415926535898
?>

PHP min() and max() Functions

The min() and max() functions can be used to find the lowest or highest value in a list of arguments:

<?php
echo(min(0, 150, 30, 20, -8, -200));  // returns -200
echo(max(0, 150, 30, 20, -8, -200));  // returns 150
?>


PHP abs() Function

The abs() function returns the absolute (positive) value of a number:

<?php
echo(abs(-6.7));  // returns 6.7
?>


PHP sqrt() Function

The sqrt() function returns the square root of a number:

<?php
echo(sqrt(64));  // returns 8
?>


PHP round() Function

The round() function rounds a floating-point number to its nearest integer:

<?php
echo(round(0.60));  // returns 1
echo(round(0.49));  // returns 0
?>


Random Numbers

Generating random numbers in PHP is easy and can be done using the rand() function or the mt_rand() function.

The rand() function generates a random integer between two specified numbers, while the mt_rand() function generates a random integer within a given range using the Mersenne Twister algorithm, which is considered to be more random than rand().

Here’s an example of how to use rand() to generate a random number between 1 and 10:

$randomNumber = rand(1, 10);
echo "The random number is: " . $randomNumber;

And here’s an example of how to use mt_rand() to generate a random number between 1 and 10:

$randomNumber = mt_rand(1, 10);
echo "The random number is: " . $randomNumber;

You can also use these functions to generate a random number within a larger range by adjusting the parameters accordingly.

It’s worth noting that if you need to generate cryptographically secure random numbers, you should use the random_int() function instead, which uses a cryptographically secure random number generator. The syntax for random_int() is the same as rand() , but it takes two integers as arguments instead of two numbers.

Scroll to Top