简体   繁体   中英

How can i echo only once inside a foreach loop PHP

I was wondering how can I echo only once inside a PHP foreach loop? Here is my code:

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;

Basically whats inside the "//echo only once" is what I want to echo only once while the the loop is less than the number 8. How can I do this?

If i understand the question correctly, why not pull the pieces you don't need iterated outside of the loop?

//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 

If i get your question right, u wish to echo header and footer only once
use a flag variable for it

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM