Page 1 of 1

Controlling a loop

Posted: Thu Aug 14, 2003 2:01 pm
by dstefani
Hello,
I'm trying to loop through an array using foreach().
When I come to a particular value, I want to skip it and go back to looping with my foreach() on the next value after the one I skipped.

Also, when I get to another particular value I'll want to bail out of the foreach all together.

I know how to do this in Perl, (next, last) but I'm not sure how to do it in PHP.

Thanks,
- D

Posted: Thu Aug 14, 2003 3:08 pm
by dstefani
I answered my own question, very cool:

Code: Select all

while (list($k,$v) = each($arrKeywords))
    {
        $v = preg_replace ('(\r\n|\r|\n)', '', $v);    
              
        if($v == 'Costume')continue;
        if($v == 'Theatrical')continue;
        if($v == '---BEGIN COSTUME ONLY---')break;
        echo "<option value="$v">$v</option>\n";
    &#125;
Thanks,
- D

Posted: Thu Aug 14, 2003 3:55 pm
by Galahad
You can use continue and break in a regular foreach loop. That might be easier to read than the while with the list/each. Not a big deal though, just thought I'd point it out. Your first post sounded like you were using foreach, why'd you switch?

Posted: Thu Aug 14, 2003 4:04 pm
by dstefani
I wasn't sure I could use it in a foreach, the place in the manual that I found the help was in the notes under 'next' (as in my post)..
to qoute the note, "If your a perl person trying to figure out how to iterate to the next loop in a while , or foreach loop, please see the 'continue' function. next is only for arrays."

So I tried the while, I saw how continue and break where just like next and last in Perl and it worked. So I'm on to the next thing.

Thanks,
-D