ConFoo Montreal 2017 Calling for Papers

# abs

(PHP 4, PHP 5, PHP 7)

absValeur absolue

### Description

number abs ( mixed `\$number` )

Retourne la valeur absolue du nombre `number`.

### Liste de paramètres

`number`

La valeur numérique à traiter

### Valeurs de retour

La valeur absolue du nombre `number`. Si le nombre est un nombre à virgule flottante (float), le type retourné est aussi un nombre à virgule flottante (float), sinon, c'est un entier (entier).

### Exemples

Exemple #1 Exemple avec abs()

``` <?phpecho abs(-4.2); // 4.2 (double/nombre à virgule flottante)echo abs(5);    // 5 (entier)echo abs(-5);   // 5 (entier)?> ```

### User Contributed Notes 4 notes

eep2004 at ukr dot net
1 month 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.40610.96970.2805Conclusion: better to check before using the feature that the number is less than zero. Even better use multiplication by -1 than this function. ```
-41
alex.khimich.org
2 years ago
``` Few ways to convert values to negative<?php// Multiplying by "-1"\$v = -1 * abs(\$v);// Using ternary operator\$v = \$v <= 0 ? \$v : -\$v;?> ```
-39
Ister
8 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. ```
-62
svein dot tjonndal at gmail dot com
5 years ago
``` If you don't have/want GMP and are working with large numbers/currencies: <?php function mb_abs(\$number) {   return str_replace('-','',\$number); } ?> No need to worry about encoding, as your numbers should all be basic (ANSI) strings. ```