abs

(PHP 4, PHP 5, PHP 7, PHP 8)

absValor absoluto

Descrição

abs(int|float $num): int|float

Retorna o valor absoluto do num.

Parâmetros

num

O valor numérico para processar

Valor Retornado

O valor absoluto de num. Se o argumento num é do tipo float, o número retornado também é float, em outro caso será int (mas poderá retornar float se o resultado tiver magnitude maior que int).

Changelog

Versão Descrição
8.0.0 num não aceita objetos internos que suportem conversão numérica

Exemplos

Exemplo #1 Exemplo da abs()

<?php
var_dump
(abs(-4.2));
var_dump(abs(5));
var_dump(abs(-5));
?>

O exemplo acima produzirá:

float(4.2)
int(5)
int(5)

Veja Também

add a note

User Contributed Notes 1 note

up
7
eep2004 at ukr dot net
2 years 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.
To Top