Math functions can be considered as programming heart or brain: they are paramount to resolve any and all logical problems that may arise. In PHP, the mathematical operators are worked out very simply, also in a standardized way like in other languages.
Then we go to a simple example that shows how the operations can be performed:
$var2 = 2;
$var = $var2 +2; // Sum
$var = $var2 -2; // Subtraction
$var = $var2/2; // Division
$var = $var2*2; // Multiplication
Note that the mathematical operators do not change, all to facilitate the assimilation and the lives of those who need to solve complex problems.
Besides the basic operators, the language still offers some ready calculations. The main ones will be showed now, all aimed at making programmer’s life easier.
This function returns the absolute value of a variable, as shown in the example:
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5); // $abs2 = 5; (interger)
$abs3 = abs(-5); // $abs3 = 5; (interger)
This function rounds the value reported to the nearest integer, according to a mathematical rule. As shown in the example:
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
This function rounds the fractional values to the lowest value, for example:
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
From the numbers of an array, the function checks which one is bigger, as the example:
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
From the number of an array, the function checks which one is the smallest, as the example:
echo min(1, 3, 5, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
This function returns a random value. If the start and end parameters are informed, the generated value will be in the range between them. For example:
echo mt_rand() . “n”;
echo mt_rand() . “n”;
echo mt_rand(5, 15);
The above example will output something similar to:
The square root calculation can be done using this function, as shown in the example:
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 …
A number of other functions can be found in the official documentation of the language. The ones shown above are the most common, used for solving practically all kinds of calculations. Anyway, it is important to know and get referrals as a particular problem may have a ready solution. So, knowing where to seek information turns out to be highly relevant and productive.
Check out more content on our blog!
Learn all about Scriptcase.
You might also like…