abs() is a PHP built-in function, defined as follows:
int|float abs ( int|float $number )
It accepts an integer or floating point number as an argument, returning the absolute value of that number.
Example:
<?php
echo abs(-10); // Output 10
echo abs(5); // Output 5
echo abs(-3.14);// Output 3.14
?>
The abs() function is only valid for numeric types. If you pass in a string, array, or other type, it will cause a warning or exception.
<?php
echo abs("abc"); // Warning: A non-numeric value encountered
echo abs([1, 2]); // Warning: A non-numeric value encountered
?>
Solution: Use is_numeric() to determine whether the variable is a numeric value first, and avoid an error when calling abs() .
<?php
$value = "abc";
if (is_numeric($value)) {
echo abs($value);
} else {
echo "The input is not a number";
}
?>
When abs() processes floating point numbers, accuracy may be lost due to the storage method of PHP floating point numbers.
<?php
echo abs(-0.000000000123456789);
?>
The output may differ slightly from expected.
Solution: Use BCMath extension or string processing to ensure high-precision numerical calculations.
In some cases, PHP treats -0 as 0, resulting in confusion in logical judgments.
<?php
$val = -0;
var_dump(abs($val)); // Output int(0)
?>
Although the output of abs(-0) is in line with the mathematical definition, it may be necessary to distinguish in some special scenarios.
Solution: This is usually rare. If the business needs to distinguish, you can judge by string or type cast by type.
<?php
$numbers = [-1, -2, 3, -4];
$absNumbers = array_map('abs', $numbers);
print_r($absNumbers);
?>
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
<?php
if (isset($_GET['num']) && is_numeric($_GET['num'])) {
$num = $_GET['num'];
echo "The absolute value is:" . abs($num);
} else {
echo "Please provide valid numerical parameters。";
}
?>
Access link example:
http://gitbox.net/abs.php?num=-15