如果使if语句忽略var为0?

时间:2015-07-29 11:04:37

标签: php if-statement ignore zero

我想检查一个变量是否大于x,除非它是0。

所以例如。

<?php
$max_n=10;//user setting maximum number of loops, infinite? choose 0.


//the problem is that 0 is the smallest number, so the loop stops immediately

for ($x = 0; $x <= $max_n; $x++) {
    $total_n=$x;
}

//if total number exceeds max amount of numbers, do something
if(1==1 || $total_n > $max_n )
{
    die('Total number is greater than max numbers!');
}

&GT;

显然无限循环是一个坏主意,但这不是重点。

如果max_n = 0

,如何使if语句忽略max_n

3 个答案:

答案 0 :(得分:2)

您可以使用continue;语句跳转到某些条件的下一条记录。

for ($x = 0; $x <= $max_n; $x++) {
  if($max_n===0){
    continue;
  }
    $total_n=$x;
}

答案 1 :(得分:1)

//if total number exceeds max amount of numbers, do something

if($max_n != 0 && $total_n > $max_n )
{
    die('Total number is greater than max numbers!');
}

答案 2 :(得分:0)

这对我有用:

<?php
$max_n=10;//user setting maximum number of loops, infinite? choose 0.


//the problem is that 0 is the smallest number, so the loop stops immediately

for ($x = 0; $x <= $max_n; $x++) {
    $total_n=$x;
}

//if total number exceeds max amount of numbers, do something
if(1==1 || ( $total_n > 0 && $total_n > $max_n ) )
{
    die('Total number is greater than max numbers!');
}
?>