Reputation: 31
Recently, I was trying to use if condition inside foreach loop .. and it has been done without issues..
But, when I use else inside the loop .. the if condition becomes fully ignored and the else condition will be executed without checking the if condition ..
Here is the loop :
foreach ($ids as $id) {
if (substr($id, 0, 8) === $first8) {
$matched = true;
header("Location: success.php");
break;
} else {
echo "<script language=\"JavaScript\">\n";
echo "alert('Entered ID is incorrect');\n";
echo "window.location='index.html?loginFailed=true&reason=wrongID'";
echo "</script>";
exit;
}
}
Now when the user enter his ID.. the else condition will be executed without if condition.. weather the ID is correct or not .. Noting that when I remove the else the code is working perfectly if the ID is correct..
Any ideas?
Upvotes: 0
Views: 1271
Reputation: 47991
Put your "no matches" process after the loop and exit;
if a match is found -- instead of break
.
foreach ($ids as $id) {
if (strpos($id,$first8)===0) {
header("Location: success.php");
exit;
}
}
echo "<script language=\"JavaScript\">\n";
echo "alert('Entered ID is incorrect');\n";
echo "window.location='index.html?loginFailed=true&reason=wrongID'";
echo "</script>";
exit;
Upvotes: 0
Reputation: 1840
Your code check only first element of the array. Use this code:
if(in_array($first8, array_map(function($id){
return substr($id, 0, 8);
}, $ids))) {
header("Location: success.php");
} else {
echo "<script language=\"JavaScript\">\n";
echo "alert('Entered ID is incorrect');\n";
echo "window.location='index.html?loginFailed=true&reason=wrongID'";
echo "</script>";
exit;
}
Upvotes: 1