How would I stop this foreach loop after 3 iterations? [duplicate]

With the break command.

You are missing a bracket though.

$i=0;
foreach($results->results as $result){
//whatever you want to do here

$i++;
if($i==3) break;
}

More info about the break command at: http://php.net/manual/en/control-structures.break.php

Update: As Kyle pointed out, if you want to break the loop it’s better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)

The code would be:

for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}

It’s cleaner, it’s more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.

Leave a Comment