stack01
stack01

Reputation: 101

How to exit a loop on condition?

$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
    $i=0;
    if($i==1||$i==2){continue;}
    echo $value;
    $i++;
}

I am a newbie of PHP, now i do a test, and i want to go out the loop not output 2 and 3, why the above code doesn't work?

Upvotes: 0

Views: 187

Answers (1)

Madara's Ghost
Madara's Ghost

Reputation: 175017

That's because you set $i = 0; on each iteration (Hence your check for $i==1||$i==2 will never match). Variable initialization go outside the loop:

$arr = array(1, 2, 3, 4);
$i   = 0;
foreach ($arr as $value) {
    if ($i == 1 || $i == 2) {
        continue;
    }
    echo $value;
    $i++;
}

Upvotes: 7

Related Questions