簡體   English   中英

在foreach循環(PHP)中正確使用else作為if條件

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

最近,我試圖在ifeach循環中使用if條件,並且它已經完成而沒有問題。

但是,當我在循環中使用else時,if條件將被完全忽略,而else條件將在不檢查if條件..的情況下執行。

這是循環:

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

 }

現在,當用戶輸入他的ID ..時,將執行else條件,而無需if條件..weather,ID是否正確..注意,當我刪除else時,如果ID是正確的,代碼將正常工作。

有任何想法嗎?

您的代碼僅檢查數組的第一個元素。 使用此代碼:

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

將您的“不匹配”過程放在循環之后並exit; 如果找到匹配項-而不是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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM