abs() is one of the built-in mathematical functions in PHP, which is used to return a number. Absolute value refers to the distance from a number to 0, so whether the original number is positive or negative, the result is always non-negative.
abs(float|int $num): float|int
$num : The number to be processed, the type can be an integer or a floating point number.
Returns the absolute value of the input value. If the input is a positive number or zero, it will return as it is; if it is a negative number, it will return its positive form.
<?php
echo abs(-10); // Output:10
?>
<?php
echo abs(-3.1416); // Output:3.1416
?>
<?php
echo abs(5); // Output:5
echo abs(0); // Output:0
?>
<?php
$scoreA = 85;
$scoreB = 92;
$difference = abs($scoreA - $scoreB);
echo "The difference in scores is:" . $difference; // Output:7
?>
<?php
$current = 50;
$previous = 75;
$change = abs($current - $previous);
echo "The range of change is:" . $change . " unit";
?>
In some business logic, it may be necessary to determine whether the absolute difference of a certain value exceeds a certain threshold:
<?php
$threshold = 10;
$diff = abs($a - $b);
if ($diff > $threshold) {
echo "Too big difference";
}
?>
In actual projects, if the interface returns two values, the front-end needs to display its difference without considering the positive and negative signs, it can be handled like this:
<?php
// Assume this is the data returned by the interface
$data = json_decode(file_get_contents('https://gitbox.net/api/data.json'), true);
$val1 = $data['value1'];
$val2 = $data['value2'];
$diff = abs($val1 - $val2);
echo "The data difference is:" . $diff;
?>
The abs() function does not change the original value of the variable, but only returns a new absolute value.
If a non-numeric type is passed in, PHP will attempt to perform type conversion; it is recommended to manually confirm the data type before the call to avoid unnecessary warnings or errors.
When dealing with large numerical or floating-point operations, you should pay attention to accuracy issues. You may need to combine functions such as round() and number_format() .