Breaking the nested loop

PhpLoopsNested Loops

Php Problem Overview


I'm having problem with nested loop. I have multiple number of posts, and each post has multiple number of images.

I want to get total of 5 images from all posts. So I am using nested loop to get the images, and want to break the loop when the number reaches to 5. The following code will return the images, but does not seem to break the loop.

foreach($query->posts as $post){
		if ($images = get_children(array(
					'post_parent' => $post->ID,
					'post_type' => 'attachment',
					'post_mime_type' => 'image'))
			){				
				$i = 0;
				foreach( $images as $image ) {
					..
					//break the loop?
					if (++$i == 5) break;
				}				
			}
}

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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++];
                    ..
                }               
            }
}
?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1355300View Question on Stackoverflow
Solution 1 - PhpdynamicView Answer on Stackoverflow
Solution 2 - PhpperiklisView Answer on Stackoverflow