logo

Exiting a foreach loop in PHP

logo

When developing using PHP you’ll run into differen’t type of loops; while, for, foreach. Some web developers have a personal preference and try to use that loop for pretty much everything they do. Some loops work better for differen’t things while others don’t perform very well. One of my favourite loops is the foreach loop.

One thing I ran into was exiting the loop when after say 3 items have been listed.

This is what I did:


<?php
$i=0;
foreach($files as $file) {
if ($i == 3) {
break;
} else {
$i++;
} ?>

// do stuff here

<?php
} ?>

That’s it! Of course, some people prefer to do this with a for loop:


<?php
for($i=0; $i<3; $i++) { ?>

// do stuff here

<?php
} ?>

At the end of the day it’s personal preference.

One Response to “Exiting a foreach loop in PHP”

  1. Dan says:

    Excellent, thanks for the tip. Foreach loops are my favourite but found it quite tricky to exit them.

Leave a Reply

logo
logo
© daparky.com 2009