PHP Reference ยท Math Functions
PHP abs() function
Reference for PHP abs(): return the absolute value of an integer or float, how it handles PHP_INT_MIN, negative zero and numeric strings, with examples.
abs() returns the absolute value of a number: its distance from zero, without the sign. abs(-5) is 5 and abs(5) is 5. Integers stay integers and floats stay floats.
It is handy for differences where you only care about the size (abs($a - $b)), for tolerance checks with floats, and for turning a signed delta into a magnitude.
<?php echo abs(-12); // 12 echo abs(-3.5); // 3.5
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
abs(int|float $num): int|float
| Name | Description |
|---|---|
$num |
The number. Numeric strings are converted to a number first. |
Return value: the absolute value. The result is an int for an int argument and a float for a float argument. For PHP_INT_MIN (which has no positive int counterpart) the result is a float.
Errors: a TypeError for non-numeric strings, arrays and other types that cannot be a number.
Usage notes
- Type is preserved.
abs(-3)isint(3),abs(-3.0)isfloat(3). abs(-0.0)returns0.0: the sign of negative zero is removed.- Float tolerance. Never test floats with
==; compareabs($a - $b)to a small epsilon (for example1e-9, orPHP_FLOAT_EPSILONfor values near 1). - Not for the length of strings or arrays; see
strlen()andcount(). - Complex "distance" between dates or timestamps: subtract and wrap with
abs()to get a non-negative gap. NANstaysNAN, andabs(-INF)isINF.- Named argument:
abs(num: -3).
Related
ceil()andfloor(),round(),intdiv(),fmod(), Arithmetic operators- Lessons: Math functions, Numbers