abs
(PHP 4, PHP 5, PHP 7, PHP 8)
abs — 绝对值
参数
-
number
-
要处理的数字值
返回值
number
的绝对值。 如果参数 number
是 float,则返回的类型也是 float,否则返回
integer(因为 float 通常比 integer 有更大的取值范围)。
范例
示例 #1 abs() 例子
<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5); // $abs2 = 5; (integer)
$abs3 = abs(-5); // $abs3 = 5; (integer)
?>

User Contributed Notes 1 note
eep2004 at ukr dot net ¶
1 year ago
<?php
echo 'PHP '.PHP_VERSION.'<br>';
$qty = 1000;
$arr = array();
for ($i = 0; $i < $qty; $i++){
$arr[] = rand(-100, 100);
}
$start = microtime(true);
for ($i = 0; $i < $qty; $i++){
foreach ($arr as $v){
$v = abs($v);
}
}
echo number_format(microtime(true) - $start, 4).'<br>';
$start = microtime(true);
for ($i = 0; $i < $qty; $i++){
foreach ($arr as $v){
if ($v < 0) $v = abs($v);
}
}
echo number_format(microtime(true) - $start, 4).'<br>';
$start = microtime(true);
for ($i = 0; $i < $qty; $i++){
foreach ($arr as $v){
if ($v < 0) $v *= -1;
}
}
echo number_format(microtime(true) - $start, 4).'<br>';
?>
Result:
PHP 7.1.33
0.0910
0.0710
0.0550
Conclusion: better to check before using the feature that the number is less than zero. Even better use multiplication by -1 than this function.