5 Useful mathematical functions in PHP


January 2, 2011PHP1 Comment


In recent posts, we gone through string related functions which are following :

How to encrypt a string using one way encryption

String Repeat function in PHP

How to find duplicate words in a string

How to encrypt password using MD5

Here we are going to see 5 mathematical functions which are common in use and  are very useful to PHP programmers.

1) Rand():

This function is used to generate random number. It accepts two parameters: a) Upper limits b) Lower Limits There is another function called getrandmax() which generates maximum value that rand() could possibly generate on our system .

Sample code :


echo rand();

echo rand(0,50);


2) uniqid()

This function is used to generate unique idenitifier . It returns alphanumeric string. It is totally based on time .


//generate a unique id


echo $id;


3) number_format()

    This Function is used to format large or floating-point numbers . It inserts comma’s between every group of thousands . Output of this function is string ,not a number .It cant be used for further manipulation. It accepts min of one parameter and max of 4 parameters . Generally we use this function with 2 parameters.



//output :10,200.00

echo $formattednum;.


First parameter is the number which is to be formatted and second parameter is the number of decimal places .

4) deg2rad()

This function is used to convert an angle measurements from degrees to radians . Formula to convert degree to radians is D=R*180/pi.But PHP has inbuilt function in it .




echo "$degrees=$radians";


We can also convert radians to degree through rad2deg().

5) Round():

It is used to round the number to a specified number of decimal places. It will return the closest integer value .



//result is 1

echo "$r";


There are other functions like ceil() and floor() which are similar to round().

The ceil() function returns the value of a number rounded UPWARDS to the nearest integer whereas floor() returns the value of a number rounded DOWNWARDS.

One Response to “5 Useful mathematical functions in PHP”
  1. sureshpeters

    thanks for the tips mate

Leave a Reply