abs
(PHP 4, PHP 5)
abs — Absolute value
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
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5); // $abs2 = 5; (integer)
$abs3 = abs(-5); // $abs3 = 5; (integer)
?>
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Математические расширения
- Математические функции
- abs
- acos
- acosh
- asin
- asinh
- atan2
- atan
- atanh
- base_convert
- bindec
- ceil
- cos
- cosh
- decbin
- dechex
- decoct
- deg2rad
- exp
- expm1
- floor
- fmod
- getrandmax
- hexdec
- hypot
- intdiv
- is_finite
- is_infinite
- is_nan
- lcg_value
- log10
- log1p
- log
- max
- min
- mt_getrandmax
- mt_rand
- mt_srand
- octdec
- pi
- pow
- rad2deg
- rand
- round
- sin
- sinh
- sqrt
- srand
- tan
- tanh
Коментарии
<?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.