PHP Math
Math functions are ready-made tools that do common calculations on numbers. Each one takes numbers in and hands back a number to print or store.
abs drops the minus sign
<?php
echo abs(-4), "\n";max and min pick the ends
<?php
echo max(2, 7), "\n";
echo min(2, 7), "\n";round goes to the nearest whole
<?php
echo round(3.6), "\n";
echo round(3.4), "\n";sqrt finds the square root
<?php
echo sqrt(25), "\n";intdiv divides whole on purpose
intdiv divides and keeps only the whole part of the answer.
<?php
echo intdiv(7, 2), "\n";Example
<?php
$side = sqrt(pow(3, 2) + pow(4, 2));
echo $side, "\n";Key points
- A math function packages a common calculation on numbers.
- Use abs to drop the minus sign from a negative number.
- Use max to pick the largest value from a set of numbers.
- Use min to pick the smallest value from a set of numbers.
- round moves a float to the nearest whole number.
- sqrt gives the square root of a number.
- pow raises a number to a power, so pow(2, 3) multiplies 2 by itself 3 times.
In this example, pow(3, 2) gives 9 and pow(4, 2) gives 16. The sum inside sqrt is 25, and sqrt(25) gives 5. That 5 is the hypotenuse, the longest side of the 3-4-5 triangle.
Note
intdiv always gives a whole number, while plain division gives a float when the result is not whole.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
What does echo intdiv(9, 2); print?