PHP abs() Function


Definition and Usage

The abs() function is an in-built function in PHP iterpreter. This function accepts any number as argument and returns a positive value, disregarding its sign. Absolute value of any number is always positive.

This function always returns positive number.

Syntax

abs( mixed $num)

Parameters

Sr.NoParameter & Description
1num
This parameter stores a value whose absolute value is to be obtained.

Return Values

PHP abs() function returns absolute value of num. If data type of num is float, return type is also float.For integer parameter, return type is integer.

PHP Version

This function is available in PHP versions 4.x, PHP 5.x as well as PHP 7.x.

Example

 Live Demo

Following example shows that absolute value of negative as well as positive float number is a positive float.

<?php
   $num=-9.99;
   echo "negative float number: " . $num . "
";    echo "absolute value : " . abs($num) . "
";    $num=25.55;    echo "positive float number: " . $num . "
";    echo "absolute value : " . abs($num); ?>

Output

This will produce the following result −

negative float number: -9.99
absolute value : 9.99
positive float number: 25.55
absolute value : 25.55

Example

 Live Demo

Following example shows that absolute value of negative as well as positive integer number is a positive integer.−

<?php
   $num=-45;
   echo "negative integer number: " . $num . "
";    echo "absolute value : " . abs($num) . "
";    $num=25;    echo "positive integer number: " . $num . "
";    echo "absolute value : " . abs($num); ?>

Output

This will produce the following result −

negative integer number: -45
absolute value : 45
positive integer number: 25
absolute value : 25

Example

 Live Demo

The abs() function returns 0 for a string parameter −

<?php
   $num="Hello";
   echo "String: " . $num . "
";    echo "absolute value : " . abs($num) . "
"; ?>

Output

This will produce the following result −

String: Hello
absolute value : 0

Updated on: 11-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements