如果多个条件为真,如何多次执行迭代?

时间:2014-09-18 06:26:10

标签: php

我有一个像这样的“if”语句:

if( (first condition) || (second condition) || (third condition) ){

//line of code

}

如果满足所有3个条件,我希望代码行运行3次。如果只满足2个条件,它必须运行2次,依此类推。

这种语法也很好:

if(){}elseif(){}elseif(){}

5 个答案:

答案 0 :(得分:7)

true将被评估为1,false为0:

$qty = (first condition) + (second condition) + (third condition);

含义$qty将包含所需的迭代次数。

所以,你执行你的命令,如下:

for ($i=0; $i<$qty; $i++) {
  //Your line of code you want to execute, for example:
  echo $i, "\n";
}

不需要明确的 if-else表达式。

答案 1 :(得分:2)

您可以先计算执行次数,然后使用循环:

$times = 0;
if (first condition) ++$times;
if (second condition) ++$times;
if (third condition) ++$times;

for (... 1 .. $times ...) do_your_thing();

答案 2 :(得分:2)

通常情况下,如果条件是短路的,那就意味着如果满足其他条件之前的条件,那么后者将永远不会执行。

参考:http://php.net/manual/en/language.operators.logical.php

所以在你的情况下,我认为你应该用其他方法重构代码,Jeremy Miller的答案似乎适用于你的情况。

答案 3 :(得分:2)

这里count变量抓住了多少条件为真。 而for循环将执行代码等于该计数($ count)。

    $count = 0 ;
    if( first condition ){

        $count++;

    }
    if( second condition ){

        $count++;

    }
    if( third condition ){

        $count++;

    }
    for($i=0;$i<$count;$i++) {
        //line of code
    }

答案 4 :(得分:1)

你可以将一个变量带到一个变量所有条件值。然后用loop运行。我认为这是最短的方法。

相关问题