PHP abs() function


The abs() function in PHP returns the absolute value of a number. The absolute value of a number is its non-negative value, which means it removes any negative sign if the number is negative.

Syntax:

abs(mixed $number): number
  • $number: The number whose absolute value you want to find. It can be an integer or a floating-point number.
  • Return Value: Returns the absolute value of the input number.

Example 1: Absolute Value of a Positive Integer

<?php echo abs(10); ?>

Output:

10

Explanation: Since 10 is already a positive number, the function simply returns 10.

Example 2: Absolute Value of a Negative Integer

<?php echo abs(-15); ?>

Output:

15

Explanation: The function removes the negative sign, so -15 becomes 15.

Example 3: Absolute Value of a Negative Float

<?php echo abs(-4.7); ?>

Output:

4.7

Explanation: The function converts -4.7 into 4.7 by removing the negative sign.

Example 4: Absolute Value of Zero

<?php echo abs(0); ?>

Output:

0

Explanation: The absolute value of 0 is still 0.

Example 5: Absolute Value of a Positive Float

<?php echo abs(3.14); ?>

Output:

3.14

Explanation: Since 3.14 is already positive, the function simply returns 3.14.

Key Points:

  • abs() is used when you want to ensure that a number is positive.
  • It works with both integers and floating-point numbers.
  • If the input is zero, the result will also be zero.

abs() is useful in cases where only non-negative values are needed, such as when calculating distances or ensuring positive quantities.