How would I stop this foreach loop after 3 iterations?

  • Declare a variable before the loop, initialize to 0.
  • Increment variable at the beginning of the body of for-each.
  • Check variable at the end of the body of for-each.
    • If it's 3, break.

You have to be careful with this technique because there could be other break/continue in the for-each body, but in your case there isn't, so this would work.


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.

Tags:

Php