In this lesson, you will learn about PHP Math Functions, their usage, and examples to better understand the topic.
The math functions are components of the PHP core. Numerous predefined math functions and constants are available in PHP and can be used to carry out mathematical tasks. We can use these functions without any installation.
Here is a collection of the most significant PHP math functions.
Math Function | Description |
---|---|
abs() | returns a number’s absolute (positive) value. |
rand() | makes an integer at random. |
round() | a floating-point number is rounded. |
sin() | returns a number’s sine value. |
sinh() | returns a number’s hyperbolic sine. |
max() | the highest value found in an array or the highest value among several specified values. |
min() | a function that returns the lowest value in an array or the lowest value among a range of provided values. |
is_finite() | determines whether or not a value is finite. |
is_infinite() | determines whether or not a value is infinite. |
is_nan() | determines if a value is “not-a-number.” |
bindec() | A binary number is changed into a decimal number. |
ceil() | The closest integer is used to round a number. |
PHP abs()
function returns a number’s absolute (positive) value. Let’s see an example below.
Basic syntax
abs(-5)// will return 5
Example
<?php echo(abs(-8.68)."<br>"); echo(abs(-78.78)."<br>"); echo(abs(-89)); ?>
Output
8.68 78.78 89
To determine the lowest or highest value in a list of inputs, use the min()
and max()
functions:
Basic syntax
min(1,2,3,4,5); // returns 1 max(1,2,3,4,5); // returns 5
Example
<?php echo(min(11,22,13,54,95)."<br>"); // returns 11 echo(max(11,22,13,54,-95)); // returns 54 ?>
Output
11 54
The closest integer is used to round a number.
Basic syntax
float ceil ( float $variable )
Example
<?php echo(ceil(11.234)."<br>"); // returns 12 echo(ceil(-15.24)."<br>"); // returns -15 echo(ceil(81.4)."<br>"); // returns 82 ?>
Output
12 -15 82
Fractions are rounded down by the floor()
function.
Basic syntax
float floor (float $variable)
Example
<?php echo(floor(11.234)."<br>"); // returns 11 echo(floor(-15.24)."<br>"); // returns -16 echo(floor(81.4)."<br>"); // returns 81 ?>
Output
11 -16 81
This concludes the PHP Math Functions lesson. In the next lesson, you will learn about an important data structure in PHP and programming in general, arrays!