2

I'm looping through an unknown number of containers which are using the col-md-8 Bootstrap class. I want to include next to the first iteration a col-md-4 class to offer up as a sidebar.

I need to pause the loop after the first iteration include my div then carry on looping from where it left off. Is there a php pause for the foreach loop so I can achieve this.

<?php foreach ($news as $new) : ?> <div class="col-md-8"> </div> <?php endforeach; ?> 
5
  • 2
    use a counter and set it to 0, then use a if clausule to check if counter is 0, if so add the col-md-4 column, else do nothing. Commented Dec 19, 2014 at 12:08
  • Did you try anything? It can be easier (and more valuable for you) to help if you try something, stumble upon a particular difficulty and ask about it, presenting your work. Commented Dec 19, 2014 at 12:08
  • What you are asking is literally not possible. Scripts run line-for-line; you can't pause there then go to here then go back to there. VDesign and donald123 below have your solution. Commented Dec 19, 2014 at 12:10
  • Yes I did try, I tried putting the div before the foreach and then using the bootstrap push and pull that works but when an col-md-8 is not next to the col-md-4 the rest of the iterations are pulled out of the container. I tried putting it in the foreach and using display none and display block on the first child but that's not the right way to go about. Commented Dec 19, 2014 at 12:12
  • If you want to make a sidebar you'd better split it up entirely <div class="col-md-12"><div class="col-md-8"><? // News items loop here ?></div><div class="col-md-4"><? // sidebar here ?></div></div> Commented Dec 19, 2014 at 12:13

2 Answers 2

1

You can use a if-statement

<?php $i=1; foreach ($news as $new) : ?> <div class="col-md-8"> </div> <?php if($i==1):?> <div class="col-md-4"> </div> <?php endif;?> <?php $i++;?> <?php endforeach; ?> 
Sign up to request clarification or add additional context in comments.

3 Comments

Cleaner to use if(++$i == 1):
@AmazingDreams you're right, but i think the OP is not deep enough in php to understand your line ;)
This looks good I think I'm understanding it right, run the foreach but when 'i=1' insert the col-md-4 but every iteration increase the value of 'i' so it isn't included every iteration?
0

Try this:

<?php $len = count($news); for ($i = 0; $i < $len; $i++) { if ($i == 0) { ?> <div class="col-md-4"> </div> <?php } ?> <div class="col-md-8"> </div> <?php } ?> 

1 Comment

for ($i = 0; $i < count($news); $i++) no good practice to use count() in conditions on each loop count() will be fired up!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.