PHP Math
PHP offers a collection of built-in functions specifically designed to perform various mathematical operations and calculations. These functions reside in the math extension, which is enabled by default in most PHP installations.
• PHP pi() Function
The pi() function returns the value of PI:
Example
<!DOCTYPE html> <html> <body> <?php echo(pi()); ?> </body> </html>
Output
3.1415926535898
• PHP abs() Function
The abs() function in PHP is a versatile tool for working with numbers. Here's a comprehensive explanation of its key aspects:
Example
<!DOCTYPE html> <html> <body> <?php echo(abs(-6.7)); ?> </body> </html>
Output
6.7
• PHP min() and max() Functions
The min() and max() functions in PHP are versatile tools for finding the smallest and largest values, respectively, among a given set of arguments.
Example
<!DOCTYPE html> <html> <body> <?php echo(rand()); ?> </body> </html>
Output
-200
150
• PHP round() Function
The PHP round() function in PHP is a versatile tool for rounding floating-point numbers (numbers with a decimal point) to a specified precision:
Example
<!DOCTYPE html> <html> <body> <?php echo(round(0.60) . "<br>"); echo(round(0.50) . "<br>"); echo(round(0.49) . "<br>"); echo(round(-4.40) . "<br>"); echo(round(-4.60)); ?> </body> </html>
Output
1
1
0
-4
-5
• PHP sqrt() Function
The PHP sqrt() Function is a built-in mathematical function used to calculate the square root of a number :
Example
<!DOCTYPE html> <html> <body> <?php echo(sqrt(64) . "<br>"); echo(sqrt(0) . "<br>"); echo(sqrt(1) . "<br>"); echo(sqrt(9)); ?> </body> </html>
Output
8
0
1
3
• Random Numbers
The rand() function generates a random number:
Example
<!DOCTYPE html> <html> <body> <?php echo(rand()); ?> </body> </html>
Output
1381167960
To get more control over the random number, you can add the optional min and max parameters to specify the lowest integer and the highest integer to be returned.
Let's see the some important PHP math functions.
• sin() - It is used to return the sine of a number.
• bindec() - It is used to convert a binary number to a decimal number.
• decbin() - It converts a decimal number to a binary number.
• exp() - It is used to calculate the exponent of e.
• floor() - It converts round a number down to the nearest integer.
• is_finite() - To check whether a value is finite or not.
• log() - It is used to return the natural logarithm of a number.
• pow() - It is used to return x raised to the power of y.