PHP Tutorial Tutorials - PHP Math Operations

PHP Math Operations

PHP provides several built-in functions that help you perform calculations.

<?php
    echo 12 + 4; // prints: 16
    echo 12 - 4; // prints: 8
    echo 12 * 4; // prints: 48
    echo 12 / 4; // prints: 3
    echo 12 % 4; // prints: 0
?>

use parentheses () to alter the precedence level:

<?php
    echo 12 + 4 * 3; // prints: 24
    echo (12 + 4) * 3; // prints: 48
?>

Get the Absolute value of a Number

PHP provides abs() function to get the absolute value of an integer or a float.

<?php
    function myAbs($number){
        if($number < 0){
            $number = 0 - $number;
        }
        return $number;
    }
    echo myAbs(-4.2); // 4.2 (double/float)
    echo myAbs(5);    // 5 (integer)
    echo myAbs(-5);   // 5 (integer)

    echo abs(-4.2); // 4.2 (double/float)
    echo abs(5);    // 5 (integer)
    echo abs(-5);   // 5 (integer)
?>
Date:2019-10-01 02:50:48 From:www.Lautturi.com author:Lautturi