porta325 Posted November 27, 2007 Share Posted November 27, 2007 Hey guys, can anyone tell me how can i do to stop execution of a loop if one value returns true ? Here is my script: $aaa = ("08408041333118"); $bann = array("1","2","3","4"); for ($i=0; $i < count($bann);$i++){ if ($ban = stripos($aaa,$bann[$i])){ echo "-true"; } else { echo "-false"; } } It returns -true-false-true-true , but i need the loop to stop when it finds the first occurence and only display "number found" only once outside the loop. Quote Link to comment Share on other sites More sharing options...
Orio Posted November 27, 2007 Share Posted November 27, 2007 Use "break": <?php $aaa = ("08408041333118"); $bann = array("1","2","3","4"); for ($i=0; $i < count($bann);$i++) { if ($ban = stripos($aaa,$bann[$i])) { echo "-true"; break; } else echo "-false"; } ?> Keep in mind that using breaks is not a very "clean" way to terminate a loop- it can be sometimes unclear to someone who looks at your code and tries to understand what you did. In this case it's pretty clear tho. Orio. Quote Link to comment Share on other sites More sharing options...
porta325 Posted November 27, 2007 Author Share Posted November 27, 2007 Works nice, thanks.One more question though. if ($ban = stripos($aaa,$bann[$i])){ $x="true"; break; } else { $x="false"; } } can i assign a variable to each case and then use it outside the loop like this ? Quote Link to comment Share on other sites More sharing options...
Orio Posted November 27, 2007 Share Posted November 27, 2007 You can do the same thing this way: <?php $aaa = ("08408041333118"); $bann = array("1","2","3","4"); $x = FALSE; for ($i=0; $i < count($bann);$i++) { if ($ban = stripos($aaa,$bann[$i]) !== FALSE) { $x = TRUE; break; } } ?> This also fixes the little bug you had in your if. Orio. Quote Link to comment Share on other sites More sharing options...
porta325 Posted November 27, 2007 Author Share Posted November 27, 2007 $aaa = ("08080"); $bann = array("1","2","3","4"); $x = FALSE; for ($i=0; $i < count($bann);$i++) { if ($ban = stripos($aaa,$bann[$i]) !== FALSE) { $x = TRUE; break; } } if ($x = false){ echo "false"; } else { echo "true"; } this returns true when it should return false. Can't figure out why.I removed the true values from the first string. Quote Link to comment Share on other sites More sharing options...
Orio Posted November 27, 2007 Share Posted November 27, 2007 if ($x = false) Should be if ($x == false) And remove the brackets around your string ($aaa). Orio. Quote Link to comment Share on other sites More sharing options...
porta325 Posted November 27, 2007 Author Share Posted November 27, 2007 You are trully a magician, thx alot. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.