Level:Beginner
In recent posts, we gone through string related functions which are following :
How to encrypt a string using one way encryption
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 : <?php 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 .
<?php //generate a unique id $id=md5(uniqud(rand(),true)); 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.
<?php $number=10200.00; $formattednum=number_format($number,2); //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 .
<?php $degrees=180; $radians=deg2rad($degrees); 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 .
<?php $num=2/3; $r=round($num); //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.
thanks for the tips mate