parent root
PHP: abs - Manual

abs

(PHP 4, PHP 5, PHP 7)

absAbsolute value

Description

abs ( mixed $number ) : number

Returns the absolute value of number.

Parameters

number

The numeric value to process

Return Values

The absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

Examples

Example #1 abs() example

<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5);    // 5 (integer)
echo abs(-5);   // 5 (integer)
?>

See Also

add a noteadd a note

User Contributed Notes 2 notes

up
14
eep2004 at ukr dot net
3 years ago
<?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.
up
-74
Ister
11 years ago
[*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.
To Top
parent root