Page 1 of 1

Why doesn't my foreach loop work?

Posted: Tue Apr 20, 2004 12:40 am
by Chris Corbyn
Hi,

Been looking at this for ages but I can't figure out why it doesn't work:

Code: Select all

$collective = array ('man', 'cat', 'water');

foreach ($collective as $n) {

    if ($n == 'cat') {
        $_SESSION['val1'] = 'cat';
        echo 'Success! '.$n.' found';
        echo '<a href="doit.php? '. SID .' ">Do This</a>';
        exit();
    } else {
        echo 'not found';
        exit();
    }
I just get the else statement each time except for when I change:

Code: Select all

if ($n == 'cat') {
to

Code: Select all

if ($n == 'man') {
Then that one works. It's as if it'll only read the first element in my array???

Where am I going wrong?

Posted: Tue Apr 20, 2004 1:05 am
by Steveo31

Code: Select all

$collective = array ('man', 'cat', 'water');

foreach ($collective as $n) {

    if ($n == 'cat') {
        $_SESSION['val1'] = 'cat';
        echo 'Success! '.$n.' found';
        echo '<a href="doit.php? '. $SID .' ">Do This</a>'; #missing $ sign
        exit();
    } else {
        echo 'not found';
        exit();
    }
} #missing end if

Posted: Tue Apr 20, 2004 6:51 am
by feyd
exit() stop's execution of all scripts (on this request)

Posted: Tue Apr 20, 2004 8:48 am
by Chris Corbyn
still doesn't work. Sorry never noticed the missing brace and $ they were there in the actual script. Would exit(); stop execution in a foreach loop since I thought it worked like this...

Look to see IF first element == cat, then look to see if second element == cat, then look to see if third element == cat. And only once it's done the entire loop would it move to the ELSE statement. And only when it find element which is == cat will it run the IF statement.

Tried taking all the exits out but then I get this output on the page
notfound Success! cat found Do This! not found
which made me realise that I shouldn't be using a foreach loop. I only want it to serach the array for the word cat not run the script foreach one. I beleive there's a function to do that. I'll take alook thanks :-)

Thanks.

Posted: Tue Apr 20, 2004 9:13 am
by redmonkey
in_array() will probably do your job

Posted: Tue Apr 20, 2004 10:10 am
by Chris Corbyn
Yeah that woked. Thanks :-)