PHP Echo Tutorials

Mathematical Functions

Written by phpecho.com   

In this tutorial, we will look at how to use some basic mathematical functions. Particularly, we will cover the following functions -

floor()
ceil()
min()
max()
abs()

The common factor towards all of the above functions is that they take numbers as the argument(s). The floor function accepts a single argument and returns the largest integer that is less than or equal to the argument input. For example, if the argument input is 2.4, then the output would be 2 as 2 is the largest integer less than 2.4. If the argument is 5, then the output would be 5 itself. Execute the following PHP program to try this out.

<?php
$inputOne = 3.9;
   $inputTwo = 5;
   echo ("Floor value of 3.9 is ".floor($inputOne)."<br>");
   echo ("Floor value of 5 is ".floor($inputTwo)."<br>");
   ?>

When this program is executed, then the output is -

Floor value of 3.9 is 3
Floor value of 5 is 5

which is same as what we expected.

If we do not pass a number as an argument, then these functions will assume the argument to be zero and accordingly return the output.

The ceil function is exactly opposite to the floor function. It returns the smallest integer greater than or equal to the input argument. Use the following code to check how this function works -

<?php
$inputOne = 3.9;
   $inputTwo = 5;
   echo ("Ceiling value of 3.9 is ".ceil($inputOne)."<br>");
   echo ("Ceiling value of 5 is ".ceil($inputTwo)."<br>");
   ?>

You should see the following output -

Ceiling value of 3.9 is 4
Ceiling value of 5 is 5

The min and max function take numbers as their arguments and as the name suggests return the minimum or maximum among them. Consider this example to get a clear idea on their usage.

<?php
   echo ('The minimum of 3, 5, 7, 2 and 3.4 is '.min(3, 5, 7, 2,3.4).'<br>');
   echo ('The maximum of 3, 5, 7, 2 and 3.4 is '.max(3, 5, 7, 2,3.4).'<br>');
   ?>

When this program is executed, you should expect to see the following -

The minimum of 3, 5, 7, 2 and 3.4 is 2
The maximum of 3, 5, 7, 2 and 3.4 is 7

The final function that we look at is abs(). This function takes a single argument as input. If the argument is negative, then it returns the corresponding positive number; if it is positive it just returns the number.
Consider the program below:

<?php
   echo ('If the argument to abs is -3.4, then the function returns '.abs(-3.4).'<br>');
   echo ('If the argument to abs is 3.4, then the function returns '.abs(3.4).'<br>');
   ?>

When this piece of code is executed, then this is what we get -

If the argument to abs is -3.4, then the function returns 3.4
If the argument to abs is 3.4, then the function returns 3.4

That is all in this tutorial of simple mathematical functions.