0

How can I interrupt a loop and adding an html element at each two iterations? Can a simple foreach do that or something in SPL?

<?php foreach($items as $index=>$item): ?>
     <li>$item->title</li>
     <?php if($index + 1 = 2):?>
     <div class="divider"></div>
     <?php endif;?> 
<?php endforeach;?>

html result,

<li>title 1</li>
<li>title 2</li>
<div class="divider"></div>
<li>title 3</li>
<li>title 4</li>
<div class="divider"></div>
<li>title 5</li>
<li>title 6</li>
<div class="divider"></div>

EDIT:

<li>title 1</li>
<li>title 2</li>
<li>title 3</li>
<div class="divider"></div>
<li>title 4</li>
<li>title 5</li>
<div class="divider"></div>
<li>title 6</li>
hakre
  • 193,403
  • 52
  • 435
  • 836
Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

3
<?php foreach($items as $index=>$item){ ?> 

<li>$item->title</li>

if ($index != 0 && $index%2 == 0){?><div class="divider"></div><?php} 

}?>
James
  • 2,013
  • 3
  • 18
  • 31
  • Thank you for the answer. but it produces the result in my edit above... what does this mean `$index%2`? – Run Feb 20 '13 at 17:18
  • I added 1 to the condition to get the right result I want `($index+1)%2 == 0` – Run Feb 20 '13 at 17:25
2

For this result :

<li>title 1</li>
<li>title 2</li>
<div class="divider"></div>
<li>title 3</li>
<li>title 4</li>
<div class="divider"></div>
<li>title 5</li>
<li>title 6</li>
<div class="divider"></div>

Do this with modulus 2 :

<?php 
foreach($items as $index=>$item) {
  if ($îndex % 2 = 0) {
?>
<?php // <!-- ADD HTML HERE !> ?>
<li>$item->title</li>
<?php
  } else {
?>
<li>$item->title</li>
<?php
  }
}
?>

For this result :

<li>title 1</li>
<li>title 2</li>
<li>title 3</li>
<div class="divider"></div>
<li>title 4</li>
<li>title 5</li>
<div class="divider"></div>
<li>title 6</li>

Do this with skipping the first index and modulus 2 :

<?php 
foreach($items as $index=>$item) {
  if ($îndex != 0 && $îndex % 2 = 0) {
?>
<?php // <!-- ADD HTML HERE !> ?>
<li>$item->title</li>
<?php
  } else {
?>
<li>$item->title</li>
<?php
  }
}
?>
Manu
  • 809
  • 1
  • 9
  • 28
  • Thank you Manu for the answer. but it produces the result in my edit above... may I ask - what does this mean by `$index%2`? – Run Feb 20 '13 at 17:19
  • I added 1 to the condition to get the right result I want `($index+1)%2 == 0` – Run Feb 20 '13 at 17:25
  • http://www.php.net/manual/en/language.operators.arithmetic.php : do not need to add 1 to `$index`. You need to get information about modulus operator `%`. Do you know this operator ? I cannot explain more here it could be too long and not appropriate in this forum. – Manu Feb 20 '13 at 18:48
  • `$index` start at `0` or `1` ? – Manu Feb 20 '13 at 18:56