This morning while studying, I remembered how I figured out how to stop / break a PHP foreach loop after a certain number while coding a pet project of mine. I decided to share a short tutorial explaining how this is accomplished and I just hope somebody if not today, will find it useful.
- Firstly, let’s create an Array.
$array = array("NIG" => "Nigeria", "AFR" => "Africa", "LAG" => "Lagos", "ABJ" => "Abuja" );
- Next, create two variables set with a counter and number to display argument.
$count = 0; $max = 3;
- Here is the Foreach loop
foreach ($array as $key => $value) { $count++; // increment the counter by 1 printf("%s is the acronym for %s ", $key, $value ); // display the loop content if ($count == $max) break; // stop looping if $max value is reached }
- You can always change the value of $max to the number of display content.
- Below is the full code.
< ?php $array = array("NIG" => "Nigeria", "AFR" => "Africa", "LAG" => "Lagos", "ABJ" => "Abuja" ); $count = 0; $max = 3; foreach ($array as $key => $value) { $count++; printf("%s is the acronym for %s ", $key, $value ); if ($count == $max) break; // stop looping if $max value is reached } ?>
- Below is the output of the code when run;
NIG is the acronym for Nigeria
AFR is the acronym for Africa
LAG is the acronym for Lagos