Limiting the number of times a PHP loop will run using the break command

If you’re reading this page then you’re already likely familiar with the standard PHP for, while and foreach loops. If not, then may I suggest some background reading first – http://www.php.net/manual/en/language.control-structures.php.

That said, I added a new weapon to my PHP arsenal today in the form of a better understanding of the break command.

I’ve used the break command before of course – it sits inside switch statements to stop each case running into the next one as below:
[php]

switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}

[/php]
But I didn’t realise that it can be used within any loop to stop the cycle continuing there and then.

This came in handy today when needing to perform a particular loop 8 times only. Normally one would just use a for loop, as that is what they’re -um- ‘for’, but in this instance I wanted to iterate across an array 8 times only. In essence, I wanted a foreach loop to run 8 times and then stop, regardless of how many items it contained.

Usually I would have either used array_slice() to reduce the array to 8 elements only, or introduced a counter and an if statement to my foreach loop as follows:
[php]

$i = 0;
foreach($array as $value){
if($i < 8){
echo $value;
}
$i++;
}

[/php]
Whilst this would work, it’s not an ideal solution because the foreach statement needs to perform the logical test ‘if $i < 8' for every item in the array – of which there could potentially be thousands. Which is where break comes in. Changing my foreach loop to the following…
[php]

$i = 0;
foreach($array as $value){
if(++$i == 8) break; //edit suggested by CHris
echo $value;
}

[/php]
means that as soon as the loop hits the ninth iteration (when $i is equal to 8) the break command is executed and the loop stops. No unnecessary iterations, and in my opinion much tidier code – which is always a good thing in my book!


Posted

in

,

by

Tags:

Comments

2 responses to “Limiting the number of times a PHP loop will run using the break command”

  1. CHris avatar

    Rather than “if($i == 8) break; $i++;”, you could use “if(++$i == 8) break;”. I think that’s neater still.

    And don’t forget that break can also take an argument to break out of several levels of looping at once.

    1. Neil avatar

      Good point on the neatness – I’ll edit that in. Probably a good idea to drop in a link to ‘break’ in the manual as well to cover the break level argument. Cheers Chris!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.