Skip to main content

PHP Mathematical Functions

By SamK
0
0 recommends
Topic(s)

PHP provides a collection of mathematical functions that enable you to execute various mathematical operations on numbers.

PHP pi() Function

The pi() function in PHP retrieves the value of PI.

<?php
echo pi();
?>

/*
Output:
3.1415926535898
*/

PHP min() and max() Functions

The min() and max() functions are utilized to determine the lowest or highest value within a set of arguments.

<?php
echo min(0, 50, 20, 40, -8, -200);
echo max(0, 50, 20, 40, -8, -200);
?>

/*
Output:
-200
50
*/

PHP abs() Function

The abs() function in PHP yields the absolute (positive) value of a number.

<?php
echo abs(-7.6);
?>

/*
Output:
7.6
*/

PHP sqrt() Function

The sqrt() function in PHP calculates the square root of a number and returns the result.

<?php
echo sqrt(25);
?>

/*
Output:
5
*/

PHP round() Function

The round() function in PHP rounds a floating-point number to the nearest integer.

<?php
echo round(0.80);
echo round(1.45);
?>

/*
Output:
1
1
*/

Random Numbers

The rand() function in PHP produces a random number.

<?php
echo rand();
?>

/*
Output:
1381167960
*/

To gain more control over the random number generation, you can add optional min and max parameters to specify the lowest and highest integers that should be returned.

For example, if you want a random integer between 20 and 200 (inclusive), use rand(20, 200):

<?php
echo rand(20, 200);
?>

/*
Output:
71
*/

Questions & Answers