math-默认的php函数,将负数变成0

有这样的事吗?

例如

$var = -5;
echo thefunction($var); // should be 0


$var = 5;
echo thefunction($var); // should be 5
foo asked 2020-02-13T05:29:30Z
5个解决方案
152 votes

尝试max($var,0),它将具有所需的效果。 有关更多信息,请参见手册页。

Alexander Gessler answered 2020-02-13T05:29:47Z
5 votes

不是内置的,但是这里有:

function thefunction($var){
   return ($var < 0 ? 0 : $var);
}

希望这可以帮助

Edgar Villegas Alvarado answered 2020-02-13T05:30:11Z
4 votes

在PHP中,检查整数是否为负数,然后将其设置为零是容易的,但是我正在寻找比以下更短(并且可能更快)的东西:

if ($x < 0) $x = 0;

好吧,这是一个非常快速的检查和重置过程,但是也有一个函数max可以做到这一点,并且它也可以用于数组。

$x = max(0, $x); // $x will be set to 0 if it was less than 0

max()函数返回两个指定数字中最大值的数字。

echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
echo max(0, 'hello'); // 0
echo max('hello', 0); // hello
echo max(-1, 'hello'); // hello

// With multiple arrays, max compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// If both an array and non-array are given, the array
// is always returned as it's seen as the largest
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)
loyola answered 2020-02-13T05:30:41Z
3 votes
function thefunction($number){
  if ($number < 0)
    return 0;
  return $number; 
}

这应该够了吧

Ibu answered 2020-02-13T05:31:00Z
1 votes

只是:

echo $var < 0 ? 0 : $var;
Szél Lajos answered 2020-02-13T05:31:20Z
translate from https://stackoverflow.com:/questions/6566187/default-php-function-that-turns-negative-numbers-in-0