Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo abs(-12);     // 12
echo abs(-3.5);    // 3.5

Try it

PHP Absolute values and differences

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.

PHP Strings and invalid input

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

PHP
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) is int(3), abs(-3.0) is float(3).
  • abs(-0.0) returns 0.0: the sign of negative zero is removed.
  • Float tolerance. Never test floats with ==; compare abs($a - $b) to a small epsilon (for example 1e-9, or PHP_FLOAT_EPSILON for values near 1).
  • Not for the length of strings or arrays; see strlen() and count().
  • Complex "distance" between dates or timestamps: subtract and wrap with abs() to get a non-negative gap.
  • NAN stays NAN, and abs(-INF) is INF.
  • Named argument: abs(num: -3).