11 Useful PHP Math or Arithmetic Functions

PHP

PHP is rich with inbuilt functions that can save you a lot of time and effort. There are several mathematical functions present in PHP which allows you to do a lot within a few lines.

Here are the most frequently used php math or arithmetic functions:

ceil(), floor() and round()
These three functions are used to round up numbers. The function ceil() rounds to a greater integer, floor() rounds to a lower integer and round() rounds to the nearest integer.

Example for all three:
<?php
$a = 1.2;
$b = 1.8;
$c = 1.5;
echo ceil($a).”<br />”; //returns 2
echo ceil($b).”<br />”; //returns 2
echo ceil($c).”<br />”; //returns 2
echo floor($a).”<br />”; //returns 1
echo floor($b).”<br />”; //returns 1
echo floor($c).”<br />”; //returns 1
echo round($a).”<br />”; //returns 1
echo round($b).”<br />”; //returns 2
echo round($c); //returns 2
?>

Output:
2
2
2
1
1
1
1
2
2

fmod()
This function is used to find out the remainder when one number is divided by the other. For example when 5 is divided by 2, the remainder 1 is returned. The % operator can also be used instead of this function.

Example:
<?php
$a = 5;
$b = 2;
echo fmod($a,$b); //Other way is $a%$b
?>

Output:
1

max() and min()
These two functions are used to find the maximum and minimum values from a set of numbers or arrays. Obviously, max() returns the highest number whereas min() returns the lowest.

Example:
<?php
$a=array(1,2,3,4,5);
echo max($a); //returns 5
echo “<br />”;
echo min($a); // returns 1
?>

Output:
5
1

rand()
Use this function to generate a random integer. You can specify two numbers between which the random number will be located. Random number generated can be inclusive of the two numbers that you specified.

Example:
<?php
echo rand(1,10); //random number between 1 and 10 inclusive
echo “<br />”;
echo rand(); //can be any random number
?>

Example Output:
9
534675351

pi()
This one simply generates the value of pi. You can use the value to perform other calculations.

Example:
<?php
echo pi();
?>

Output:
3.1415926535898,

pow()
Calculates the value of a certain number when it is raised by a power. The number and the power can be positive, negative or zero.

Example:
<?php
echo pow(3,2).”<br />”; //Generates 9
echo pow(3,-2).”<br />”;; //Generates 0.11111111111111
echo pow(-3,3).”<br />”;; //Generates -27
echo pow(-3,-3); //Generates -0.037037037037037
?>

Output:
9
0.11111111111111
-27
-0.037037037037037

sqrt()
This one finds the square root of numbers.

Example:
<?php
echo sqrt(9); //Generates 3;
?>

Output:
3

base_convert()
This one converts a number from one base to another. You can perform binary to octal, decimal to hexadecimal for example.

Syntax:

base_convert(number,sourcebase,targetbase);

Example:

<?
$a=10;
echo base_convert($a, 10, 2); //converts 10 in decimal to binary
?>

Output:
1010

There are tons of other php math functions. If you are looking for the entire list, click here for the official resource.