将负数变为 0 的默认 php 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6566187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:44:24  来源:igfitidea点击:

Default php function that turns negative numbers in 0

phpmathvariablesnumbers

提问by foo

Is there such a thing?

有这样的事情吗?

for eg

例如

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


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

回答by Alexander Gessler

Try max($var,0), which will have the desired effect. See the manual pagefor more information.

试试看max($var,0),会有想要的效果。有关更多信息,请参阅手册页

回答by Edgar Villegas Alvarado

Not built-in but, here you have:

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

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

Hope this helps

希望这可以帮助

回答by loyola

In PHP, checking if a integer is negative and if it is then setting it to zero is easy, but I was looking for something shorter (and potentially faster) than:

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

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

Well, this is a very quick check and reset, but there is a function max that does this too and it works with arrays too.

嗯,这是一个非常快速的检查和重置,但是有一个函数 max 也可以这样做,它也适用于数组。

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

The max() function returns the number with the highest value of two specified numbers.

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)

回答by Ibu

function thefunction($number){
  if ($number < 0)
    return 0;
  return $number; 
}

that should do the trick

这应该够了吧

回答by Szél Lajos

Simply:

简单地:

echo $var < 0 ? 0 : $var;