PHP MySQL tutorial

Math Functions in PHP

Performing mathematical operations in your code is one of the most compelling tasks. Thankfully, PHP provides built in support for majority of mathematical functions ranging from random number generation, number to hexadicmal conversion to finding square root of a number. Let’s review some of the most commonly used math functions with the help of a simple example.

  1. sqrt(): used to find square root of a number passed as parameter. For instance, sqrt(144) will return 12.
  2. Log(): used to find log of a number passed as parameter. For instance log(16) will return 2.7725.
  3. pow(): used to raise first parameter to the power of second. For example pow(2,3) will return 8.
  4. floor(): returns lower nearest value in terms of integer e.g. floor(10.8) will return 10.
  5. ceil():returns the greater nearest integer value e.g ceil(10.8) will return 11.
  6. dechex(): Used to convert normal number to hexadecimal representation. For example dechex(527) will return 20f.
  7. rand(): use to generate random numbers between first and second parameters inclusive For example rand(10,20) will return any number between the specified integers.
  8. min() and max(): Use to find minimum and maximum values from a collection of variables. For instance max(12, 45,2, 43, 56, 23, 34) will return 56 and min(12, 45,2, 43, 56, 23, 34) will return 2.
  9. round(): Use to round off a number to nearest value e.g 10.49 will be rounded off to 10.

Have a look at the following example to see these functions in action.


";

// taking log of 16
echo log($num1)."
"; // taking 16 to the power 2 echo pow($num1, $num2)."
"; // floor of 10.8 will be 10. echo floor(10.8)."
"; // Ceiling of 10.8 will be 11. echo ceil(10.8)."
"; // Finding hexadecimal value of 527 echo dechex(527)."
"; // Generating random number between 6 and 9 echo rand(2, 20)."
"; // finding maximum of 12, 45,2, 43, 56, 23, 34 echo max(12, 45,2, 43, 56, 23, 34)."
"; // finding minimum of 12, 45,2, 43, 56, 23, 34 echo min(12, 45,2, 43, 56, 23, 34)."
"; // Rounding of 10.49 to nearest integer... echo round(10.49); ?>

Download the code
Run the code

<<< Abstract Class in PHPError and Exception Handling in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .