PHP abs()函数
abs()函数返回给定数字的绝对值。它返回一个整数值,但如果你传递浮点值,它返回一个浮点值。
语法
abs(number);
Name | Description | Return type |
---|---|---|
number | Numeric value | Float/integer |
示例1
<?php
echo "The value of abs(-4.2) is: ".abs(-4.2)."<br>"; // 4.2 (double/float)
echo "The value of abs(5) is: ".abs(5)."<br>"; // 5 (integer)
echo "The value of abs(-5) is: ".abs(-5)."<br>"; // 5 (integer)
?>
输出:
The value of abs(-4.2) is: 4.2
The value of abs(5) is: 5
The value of abs(-5) is: 5
示例2
<?php
value = -123;
if (value < 0){
positive = abs(value);
echo $positive;
}
?>
输出:
123
示例3
<?php
v1= array(1,-2,4,-7.3,105);v2=array_map("abs",v1);
while (list (key, val) = each (v2)) {
echo "The array value key is =val <br>";
}
?>
输出:
The array [0] value is = 1
The array [1] value is = 2
The array [2] value is = 4
The array [3] value is = 7.3
The array [4] value is = 105
注意: array_map() 用于将数组中的所有负数转换为正数。