【问题标题】:Loop echo something every 4th time in php [duplicate]在php中每4次循环回显一些东西[重复]
【发布时间】:2014-05-19 19:40:53
【问题描述】:

我想每四次循环执行 2 次。例如,如果我想回显四次“你好”,然后再回声两次“再见”,它看起来像这样

hello
hello
hello
hello
goodbye
goodbye
hello
hello
hello
hello

.... 等等..

我已经尝试过类似的东西..

if ($x==4) {echo 'hello'; }
else {echo 'goodybe'; }

我怎样才能在 php 中做类似的事情?

我可以使用模数吗?

我只是不明白...谢谢!

【问题讨论】:

  • 这不是你在“编程入门”课上学到的吗?

标签: php loops for-loop while-loop modulo


【解决方案1】:

例如这样的:

for ($i = 0; $i < 10; $i++){
    for ($n = 0; $n < 4; $n++) {
        print "hello";
    }
    for ($m = 0; $m < 2; $m++) {
        print "goodbye";
    }
}

【讨论】:

    【解决方案2】:

    是的,您可以使用模数。用简单的算术第n次很好。当你还是个小学生的时候,你做过模数运算:它是除法问题的商的余数。当余数为零时,您已均分。

    零模整数将产生零。因此,下面的外部迭代循环从 1 开始,以便您可以跳过 $x=0 的常见基本情况。

    for ($x = 1; $x <11; $x++){
        // inside a given loop of ten iterations . . . 
    
        // determine if this is a plain case or the 4th time
        // if it is the fourth time, load a 1 in $type; otherwise, load a 0.
        $type = ((($x%4)==0)?1:0);
        // prepare to respond with hello or goodbye based on $type
        $output = (($type==0)?"hello":"goodbye");
        // echo $output once or twice based on $type
        for($i=0, $j=1+$type; $i < $j ;$i++){
            echo "<p>$x $output</p>";
    
        }
    }
    

    将生成如下输出:

    1 你好

    2 你好

    3 你好

    4 再见

    4 再见

    5 你好

    6 你好

    7 你好

    8 再见

    8 再见

    9 你好

    10 你好

    【讨论】:

      【解决方案3】:

      试试这个:

      if (($x % 6) < 4) {
        echo 'hello';
      }
      else {
        echo 'goodbye'; 
      }
      

      【讨论】:

        猜你喜欢
        • 2015-05-21
        • 1970-01-01
        • 2021-10-11
        • 2019-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-28
        相关资源
        最近更新 更多