abs() : absolute value
PHP Math Functions abs() : absolute value
Get a non-negative absolute value abs() returns the absolute value of an integer or float. It is useful when only the magnitude of a difference matters.
$difference = -18.5 ;
echo abs ($difference); // 18.5
This is the recommended starting pattern. The detailed examples below are retained and modernized for additional variations and explanation.
echo abs (-6.2 ); // Output 6.2
echo " <br> " ;
echo abs (-4 ); // Output 4
echo " <br> " ;
echo abs (3.2 ); // Output 3.2
echo " <br> " ;
echo abs (7 ); // Output 7
Changing all negative numbers of an array
We can take an array with both negative and positive numbers. We will use array_map() built in PHP function to change all negative elements to positive by using abs function.
<?Php
$a= array (1 ,-2 ,4 ,-7.3 ,105 );
$b=array_map (" abs " ,$a);
foreach ($b as $key => $val) {
echo " $key -> $val <br> " ;
}
?>
Output is here.
0 -> 1
1 -> 2
2 -> 4
3 -> 7.3
4 -> 105
Example: Handling Negative Numbers
$num = -15 ;
echo abs ($num); // Output: 15
Example: Calculating Difference Between Two Numbers
$num1 = 25 ;
$num2 = 50 ;
echo abs ($num1 - $num2); // Output: 25
Questions
What does the `abs()` function in PHP do?
What is the purpose of the `abs()` function in PHP?
How do you calculate the absolute value of a number using the `abs()` function in PHP?
Does the `abs()` function return a positive or negative value?
Can you pass non-numeric values to the `abs()` function in PHP?
What happens if you pass a negative number to the `abs()` function?
How can you use the `abs()` function to calculate the absolute value of a variable in PHP?
Are there any alternative ways to calculate the absolute value of a number in PHP besides using the `abs()` function?
Can the `abs()` function be used with floating-point numbers in PHP?
What type of value does the `abs()` function return: integer or float?
← Math Functions pow() to get exponential value →
Author & Instructor at
plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com