Breaking the nested loop [duplicate] Breaking the nested loop [duplicate] php php

Breaking the nested loop [duplicate]


Unlike other languages such as C/C++, in PHP you can use the optional param of break like this:

break 2;

In this case if you have two loops such that:

while(...) {   while(...) {      // do      // something      break 2; // skip both   }}

break 2 will skip both while loops.

Doc: http://php.net/manual/en/control-structures.break.php

This makes jumping over nested loops more readable than for example using goto of other languages


Use a while loop

<?php $count = $i = 0;while ($count<5 && $query->posts[$i]) {    $j = 0;    $post = $query->posts[$i++];    if ($images = get_children(array(                    'post_parent' => $post->ID,                    'post_type' => 'attachment',                    'post_mime_type' => 'image'))            ){                            while ($count < 5 && $images[$j]) {                 $count++;                 $image = $images[$j++];                    ..                }                           }}?>