0
$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?

2
  • 1
    use break; inside if condition Commented Aug 19, 2012 at 8:54
  • 3
    You need to use break to get out, continue is to go to the next element in iteration. see php manual for more infos. Commented Aug 19, 2012 at 8:54

1 Answer 1

7

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.