简体   繁体   中英

Correctly using else for an if condition inside foreach loop (PHP)

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?

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;    
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM