我怎样才能在foreach循环PHP中回显一次

时间:2014-12-27 05:29:08

标签: php foreach

我想知道如何在PHP foreach循环中只回显一次?这是我的代码:

foreach(range(1, $numDays) as $number):
    $counter++;
    echo $number;

    if($counter < 8){
        //echo only once bellow
        echo "<div>header</div>";
        //echo only once above          

        echo "hello";

        //echo only once below
        echo "<div>footer</div>";
        //echo only once above          
    }   
endforeach;

基本上“// echo only once”里面的内容是我想要回显一次,而循环次数小于8次。我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,为什么不拉出你不需要在循环之外迭代的部分呢?

//echo only once bellow
    echo "<div>header</div>";
//echo only once above           

foreach(range(1, $numDays) as $number):
    $counter++;
    echo $number;
    if($counter < 8){
        echo "hello";
    } 
endforeach;

//echo only once below
    echo "<div>footer</div>";
//echo only once above 

答案 1 :(得分:0)

如果我的问题是正确的,那么你希望只有一次使用标志变量来回显页眉和页脚。

foreach(range(1, $numDays) as $number):
      $counter++;
      echo $number;
      $flag=1;

      if($counter < 8){
           //echo only once bellow
           if($flag == 1)
                 echo "<div>header</div>";
           //echo only once above           


           echo "hello";


           //echo only once below
           if($flag == 1)
           {
                echo "<div>footer</div>";
               // Since you are done printing change the flag back to '0'
               $flag = 0;
           }
           //echo only once above           
      } 
  endforeach;