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

发布于 2024-11-18 07:47:02 字数 152 浏览 1 评论 0原文

有这样的事吗?

例如

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


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

Is there such a thing?

for eg

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


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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

甚是思念 2024-11-25 07:47:02

尝试 max($var,0),这将达到预期的效果。有关详细信息,请参阅手册页

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

笑忘罢 2024-11-25 07:47:02

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

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

希望这有帮助

Not built-in but, here you have:

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

Hope this helps

鲜血染红嫁衣 2024-11-25 07:47:02

在 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)

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:

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.

$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.

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)
千と千尋 2024-11-25 07:47:02
function thefunction($number){
  if ($number < 0)
    return 0;
  return $number; 
}

那应该可以解决问题

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

that should do the trick

撑一把青伞 2024-11-25 07:47:02

简单地:

echo $var < 0 ? 0 : $var;

Simply:

echo $var < 0 ? 0 : $var;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文