Debug School

rakesh kumar
rakesh kumar

Posted on

PHP Math Operations

PHP Math Operations

abs() function
ceil() function
floor() function
sqrt() function
rand() function

abs() function

<?php
echo abs(5);    // 0utputs: 5 (integer)
echo abs(-5);   // 0utputs: 5 (integer)
echo abs(4.2);  // 0utputs: 4.2 (double/float)
echo abs(-4.2); // 0utputs: 4.2 (double/float)
?>
Enter fullscreen mode Exit fullscreen mode

As you can see if the given number is negative, the valued returned is positive. But, if the number is positive, this function simply returns the number.

ceil() function and floor() function

can be used to round a fractional value up to the next highest integer value

<?php
// Round fractions up
echo ceil(4.2);    // 0utputs: 5
echo ceil(9.99);   // 0utputs: 10
echo ceil(-5.18);  // 0utputs: -5

// Round fractions down
echo floor(4.2);    // 0utputs: 4
echo floor(9.99);   // 0utputs: 9
echo floor(-5.18);  // 0utputs: -6
?>
Enter fullscreen mode Exit fullscreen mode

sqrt() function

<?php
echo sqrt(9);   // 0utputs: 3
echo sqrt(25);  // 0utputs: 5
echo sqrt(10);  // 0utputs: 3.1622776601684
echo sqrt(-16); // 0utputs: NAN
?>
Enter fullscreen mode Exit fullscreen mode

Generate a Random Number
rand() function

<?php
// Generate some random numbers
echo rand() . "<br>";
echo rand() . "<br>";

// Generate some random numbers between 1 and 10 (inclusive)
echo rand(1, 10) . "<br>";
echo rand(1, 10) . "<br>";
?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)