The abs()
function in PHP returns the absolute value of a number.
It removes any negative sign and always returns a non-negative result.
This function works with both integers and floats.
It is commonly used in financial, distance, or mathematical calculations.
For example, abs(-20)
returns 20
, and abs(5)
returns 5
.
Syntax
abs(number);
- number – A numeric value (positive or negative)
Example
File Name: abs-example.php
<?php
echo abs(-10); // ➤ Output: 10
echo abs(25); // ➤ Output: 25
echo abs(0); // ➤ Output: 0
?>
Use Cases
- Calculating distances (e.g., difference between 2 values)
- Removing negative signs
- Financial calculations (e.g., absolute profit/loss)
$profit = -500;
echo "Total Loss: " . abs($profit); // ➤ 500
Summary
Function | Purpose |
---|---|
abs() |
Returns non-negative value of a number |