The abs() function in PHP is used to return the absolute (non-negative) value of a number.
Syntax:
abs(number)
- number: A numeric value. It can be positive, negative, or zero.
What it does:
- If the number is positive, it returns the same number.
- If the number is negative, it returns the positive equivalent.
- If the number is zero, it returns
0.
Examples:
<?php
echo abs(10); // Output: 10
echo abs(-10); // Output: 10
echo abs(0); // Output: 0
echo abs(-5.75); // Output: 5.75
?>
Use Case Example:
Let's say you want to calculate the difference between two values, and you don’t care about the order.
<?php
$actual = 80;
$expected = 100;
$difference = abs($actual - $expected);
echo "Difference is: $difference"; // Output: Difference is: 20
?>
This ensures that even if $actual is greater than $expected, you still get a positive difference.