-1

Possible Duplicate:
How would I stop this foreach loop after 3 iterations?

I have a for loop in PHP.

When a condition is met, I would like it to stop runnning, right now it still continues all the way to 10000 $i values. I want it to totally stop after it finds 6 and continue with the rest of my code.

I have:

$bigarray=...
$countrec=0;
for ($i=1;$i<10000;$i++){
    if($countrec<6){
    if(array_search($i,$bigarray)!=-1){
    echo "Test! $i<br>";
    $countrec++;
    }
    }
}

How can I stop it early?

Community
  • 1
  • 1
David19801
  • 11,214
  • 25
  • 84
  • 127

4 Answers4

1

break;

break ends execution of the current for, foreach, while, do-while or switch structure.

adlawson
  • 6,303
  • 1
  • 35
  • 46
0

Break

$bigarray=...
for ($i=1;$i<10000;$i++){
    if($bigarray[$i] == 999){
       break;
    }
}
abcde123483
  • 3,885
  • 4
  • 41
  • 41
0

To stop a loop you simply use a break; statement:

for ($i = 0;  $i < 10000; $i++) {
    if ($i == 666) {
      break; // will break out of the loop
    }
}
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
  • How much does this break out of? if I have this inside a while loop too, will it exit that too? I only want to stop this and the while loop... – David19801 Dec 04 '11 at 15:16
  • Yes it will break out of a foreach, for, while, switch. http://php.net/manual/en/control-structures.break.php – Cyclonecode Dec 04 '11 at 15:16
  • 3
    "break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of." e.g. `break 2;` – Aaron W. Dec 04 '11 at 15:18
0

You can just use break;

See here: PHP Manual

jagse
  • 333
  • 4
  • 18