Some Commonly Used PHP Math Functions

Some Commonly Used PHP Math Functions

·

2 min read

In this tutorial, we will be covering some commonly used PHP math functions.

These are built-in PHP that comes with PHP by default. They are a set of math functions that allow you to perform some kind of mathematical task on numbers.

The list of far from exhaustive: there are far more math functions that are less commonly used.

Pi() Function

The pi() function returns the exact value of Pi.

Example

<?php
echo(pi()); 
// returns 3.1415926535898
?>

Result

1.png Max() And Min()

The max() and min() functions look into a set of numbers and finds the maximum or minimum value of a group of numbers. Example

<?php
echo(max(0, 20, 50, 800, 178, -888));  // returns 800
echo(min(0, 30, 70, 90, -180, 400));  // returns -180
?>

Result

2.png

Abs() Function

The abs() functions returns the absolute or positive value of a number. Example

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

Result

3.png So in the above, the negative number becomes a positive one and nothing happens to the positive number.

Sqrt() Function

The sqrt() function simply returns the square root of a particular number. Example

<?php
echo sqrt(144); //returns 12
?>

Result

4.png

Round() function

Example

<?php
echo round(0.8);
echo round(19.11); //returns 20
?>

The round() function takes a number and rounds it up to the nearest integer. Result

Screen Shot 2021-10-14 at 1.08.30 PM.png So in the above example, 0.8 rounds it up to 1 and 19.11 rounds down to 10.

Random() function

A more commonly used is the random() function Simply put, random() generates a random integer (this differs to some programming languages where the random() equivalent generates a float).

Example

<?php
echo random(1, 100); //returns a random number between 1 to 100.
?>

(one possible) Result

5.png In the above example, both random() generates random numbers.

However, you can add more control to the random number by adding two parameters: the first parameter is the minimum number and the second parameter is the maximum number that can be returned.

For example, by adding 1 and 100 as the two parameters, an integer number between 1 and 100 will be returned.