abs

(PHP 4, PHP 5, PHP 7)

abs绝对值

说明

abs ( mixed $number ) : number

返回参数 number 的绝对值。

参数

number

要处理的数字值

返回值

number 的绝对值。 如果参数 numberfloat,则返回的类型也是 float,否则返回 integer(因为 float 通常比 integer 有更大的取值范围)。

范例

Example #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

eep2004 at ukr dot net 25-Jul-2016 09:28
<?php
$arr
= array();
for (
$i = 0; $i < 1000; $i++) $arr[] = rand(-100, 100);

$start = microtime(true);
for (
$i = 0; $i < 1000; $i++){
    foreach (
$arr as $v) $v = abs($v);
}
echo
number_format(microtime(true) - $start, 4).'<br />';

$start = microtime(true);
for (
$i = 0; $i < 1000; $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 < 1000; $i++){
    foreach (
$arr as $v) if ($v < 0) $v *= -1;
}
echo
number_format(microtime(true) - $start, 4).'<br />';
?>
Result:
1.4061
0.9697
0.2805

Conclusion: better to check before using the feature that the number is less than zero. Even better use multiplication by -1 than this function.
Ister 17-Jul-2008 01:59
[*EDIT* by danbrown AT php DOT net: Merged user's corrected code with previous post content.]


jeremys indicated one thing - there is no sgn function wich actually seems a bit strange for me. Of course it is as simple as possible, but it is usefull and it is a standard math function needed occasionally.

Well, I have solved this function in a bit different matter:

<?php

function sgn($liczba)
{
    if(
$liczba>0)
       
$liczba=1;
    else if(
$liczba<0)
       
$liczba=-1;
    else if(!
is_numeric($liczba))
       
$liczba=null;
    else
       
$liczba=0;
    return
$liczba;
}

?>

The difference is that it returns null when the argument isn't a number at all.