PHP abs() Function

Quick summary: The PHP abs() function returns the absolute value of a number.

PHP abs() Syntax

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

PHP abs() Basic examples

$number = -15;
echo abs($number);
PHP
Output:
15

Returns the absolute (positive) value of a number.

echo abs(10);
PHP
Output:
10

If the number is already positive, it remains unchanged.

echo abs(-3.7);
PHP
Output:
3.7

Works with floating-point numbers as well.

PHP abs() Real-world usage

$a = 5;
$b = 12;
$distance = abs($a - $b);
echo $distance;
PHP
Output:
7

Calculates the distance between two numbers.

$temperatureChange = -8;
echo "Change: " . abs($temperatureChange);
PHP
Output:
Change: 8

Displays absolute difference regardless of direction.

PHP abs() Edge cases

echo abs(0);
PHP
Output:
0

Zero remains zero.

echo abs(PHP_INT_MIN);
PHP
Output:
int overflow possible

On some systems, abs(PHP_INT_MIN) may overflow because the positive value cannot be represented.

PHP abs() Common mistakes

Expecting abs() to change the original variable

abs() returns a value but does not modify the original variable.

Incorrect
$number = -5;
abs($number);
echo $number;
Correct
$number = -5;
$number = abs($number);
echo $number;

Assign the result back if you want to update the variable.

PHP abs() Frequently Asked Questions

What does abs() do in PHP?

Returns the absolute value of a number.

Does abs() work with floats?

Yes.

Use case?

Ensuring positive values.

Can abs() return negative?

No.

Handles zero?

Yes.

Performance?

Very fast.

Common mistake?

Expecting sign preservation.

Works with strings?

Numeric strings only.

Return type?

int or float.

Alternative?

Manual check.

Safe?

Yes.

Best practice?

Use for normalization.

PHP abs() Related PHP Functions