CodeIgniter Forums
breaking for each loop - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: breaking for each loop (/showthread.php?tid=60455)



breaking for each loop - El Forum - 03-30-2014

[eluser]Bigil Michael[/eluser]
i would like to know is it possible to break a foreach loop like this.
first i want to print 1-5 then echo some static content
then i want to print 6-10 after that echo some static content
then i want to print 11-15 .

is it possible?? suggestions please.....


breaking for each loop - El Forum - 03-31-2014

[eluser]Bigil Michael[/eluser]
any suggestions ??


breaking for each loop - El Forum - 03-31-2014

[eluser]jonez[/eluser]
If you want the same thing between each group:
Code:
$i = 0;

foreach ( $arr as $item ) {
if ( $i % 5 == 0 ) {
  echo '--';
}

echo $item;

$i++;
}

If you want something different between each group:
Code:
$i = 0;

foreach ( $arr as $item ) {
if ( $i == 5 ) {
  echo '--';
}
else if ( $i == 10 ) {
  echo '**';
}

echo $item;

$i++;
}



breaking for each loop - El Forum - 04-01-2014

[eluser]Bigil Michael[/eluser]
sorry it will not work for me.
my requirements is to stop the execution of loop at 5 and start the execution from 6. in between 5 and 6 i want to print some static contents.


breaking for each loop - El Forum - 04-01-2014

[eluser]jonez[/eluser]
[quote author="Bigil Michael" date="1396350530"]sorry it will not work for me.
my requirements is to stop the execution of loop at 5 and start the execution from 6. in between 5 and 6 i want to print some static contents.[/quote]
Why? Stopping and restarting or checking and printing between iterations will accomplish the same thing.

If it's a numeric array you could do this instead, but it will produce the same output and is a lot more code:
Code:
for ( $i = 0, $len = 5; $i < $len; $i++ ) {
    echo $arr[ $i ];
}

echo '--';

for ( $i = 5, $len = 10; $i < $len; $i++ ) {
    echo $arr[ $i ];
}

echo '--';

for ( $i = 11, $len = 15; $i < $len; $i++ ) {
    echo $arr[ $i ];
}