Performing Math Operations
PHP has many built-in functions that help you do anything from simple addition or subtraction to advanced computation.
Each math operation has a certain precedence level; Multiplication and division are usually done before addition and subtraction. However, parentheses can change this precedence; Sentences enclosed within parentheses are always evaluated, regardless of prior level of operation, as in the following example.
In the following section we’re going to look at some built-in PHP functions that are most frequently used in performing mathematical operations.
Find the Absolute Value of a Number
The absolute value of an integer or float can be found with the abs () function, as shown in the following Example:
As you can see if the given number is negative or not, the valued return is positive. But, if the number is positive, this function only returns the number.
Round a Fractional Value Up or Down
The ceiling () function can be used to round a fractional value to the next highest integer value, while the floor () function can be used to round a fractional value to the next lowest integer value, As shown in the following Example:
Find the Square Root of a Number
You can use the sqrt () function to find the square root of a positive number. This function returns a special value NAN for negative numbers.
Generate a Random Number
The rand () function can be used to generate a random number. You can optionally specify a range by passing minimum, maximum arguments,
If the rand () function is called without optional minimum, maximum arguments, it returns a pseudo dimensional number between 0 and getrandmax (). The getrandmax () function shows the largest possible random value, which is only 32767 on the Windows platform. Therefore, if you need a range larger than 32767, you can specify only minimum and maximum arguments.