PHP abs() function
The abs()
function in PHP returns the absolute value of a number. The absolute value of a number is its non-negative value, which means it removes any negative sign if the number is negative.
Syntax:
- $number: The number whose absolute value you want to find. It can be an integer or a floating-point number.
- Return Value: Returns the absolute value of the input number.
Example 1: Absolute Value of a Positive Integer
Output:
Explanation: Since 10
is already a positive number, the function simply returns 10
.
Example 2: Absolute Value of a Negative Integer
Output:
Explanation: The function removes the negative sign, so -15
becomes 15
.
Example 3: Absolute Value of a Negative Float
Output:
Explanation: The function converts -4.7
into 4.7
by removing the negative sign.
Example 4: Absolute Value of Zero
Output:
Explanation: The absolute value of 0
is still 0
.
Example 5: Absolute Value of a Positive Float
Output:
Explanation: Since 3.14
is already positive, the function simply returns 3.14
.
Key Points:
abs()
is used when you want to ensure that a number is positive.- It works with both integers and floating-point numbers.
- If the input is zero, the result will also be zero.
abs()
is useful in cases where only non-negative values are needed, such as when calculating distances or ensuring positive quantities.