Returns the absolute value of a number, removing its negative sign.
What Is abs() in PHP?
Returns the absolute value of a number, removing its negative sign.
Its syntax is:
abs(int|float $num): int|float
Parameters:
$num— Accepted as int|float; required argument.
Return type: int|float. The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.
Availability: Available in standard PHP.
Example 1: Basic Usage
<?php
echo abs(-18);
Output:
18
The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.
Example 2: A Different Input
<?php
echo abs(-3.75);
Output:
3.75
The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.
Practical Example: Applying It in a Program
<?php
$balances = [-35.5, 12.0, -8.25];
foreach ($balances as $balance) { echo abs($balance) . PHP_EOL; }
Output:
35.5
12
8.25
The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.
Important Behavior and Edge Cases
- Key behavior: The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.
- Environment: Available in standard PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
abs() | returns the absolute value of a number, removing its negative sign. |
max() | max() selects the largest of supplied values; abs() returns the magnitude of one number. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: The return type follows the numeric input | The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer. |
Key Takeaways
- returns the absolute value of a number, removing its negative sign.
- The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.
- Available in standard PHP.
Summary: The return type follows the numeric input. The minimum platform integer can produce a floating-point result because its positive counterpart may not fit in an integer.