user983248
user983248

Reputation: 2688

stop script or loop after first match without using exit;

no idea how to ask this question... the problem is that I need to stop the loop from runing if if ($current[$id][$i]['item'] == '') is true, so whatever the script needs to do or in this case echo, don't get repeated 15 times.

If using exit; the whole page will stop to render, so, any ideas ?

Thanks in advance.

If the question is not clear enough don't hesitate to ask using the comments, I will more than happy to clarify any doubts.

$i=1; 
while($i<=15) { 
    if ($current[$id][$i]['item'] == '') { 
        echo 'Done!.';
        //do something
    } 
    $a++; 
}

Upvotes: 0

Views: 10091

Answers (5)

Gryphius
Gryphius

Reputation: 78956

use break

$i=1; 
while($i<=15) { 
    if ($current[$id][$i]['item'] == '') { 
        echo 'Done!.';
        break;
    } 
    $i++;  //<- that should probably be $i instead of $a?
}

Upvotes: 13

Miqdad Ali
Miqdad Ali

Reputation: 6147

$i=1; 
while($i<=15) { 
    if ($current[$id][$i]['item'] == '') { 
        echo 'Done!.';
        break;  //   or you can make value of $i = 20;
    } 
    $a++; 
}

Upvotes: -1

Brian
Brian

Reputation: 8616

There is only 2 ways to break a loop... using exit; and break;....

break; is what you want it will exit the loop and continue execution, exit will end the script.

Upvotes: 0

Mitya
Mitya

Reputation: 34576

You need to break. Also, your current loop is endless and will therefore time-out. Presumably you meant to increment $i, not $a.

$i=1; 
while($i<=15) { 
    if ($current[$id][$i]['item'] == '') { 
        echo 'Done!.';
        break; //<-- terminate loop
    } 
    $a++; //<-- shouldn't this be $i++?
}

Upvotes: 2

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120997

How about using the break control structure?

Upvotes: 3

Related Questions