使用foreach()检查用户名和密码是否匹配

时间:2018-04-03 19:36:46

标签: php

<?php
        // John123 is username, UDXddM is the password linked to that username. Same markup for all others.
        $login['John123'] = "UDX6672ddM";
        $login['Ramsey123'] = "iGO4u4234TC";
        $login['Nikita123'] = "KLWRES31BYKRBPJM";
        $login['Emma123'] = "PNYUhdhCHU34AQPSUYJ";
        $login['Anna123'] = "PNYZB512SGJkfDALT";
        $login['Peter123'] = "SNZasdVPB56HZSUhkET";
        $login['Bob123'] = "VLPBPH778UATAaGM";
        $login['Ron123'] = "FDSasArhCU90TPDSC";
        $login['Will567'] = "GQgCUF083GTZgsTFPG";
        $login['Oliver123'] = "VAGSE4234GKJXY";

        foreach()
        {

        }
        ?>

使用foreach循环我想看看用户名是否与密码匹配(例如,如果我在登录页面输入用户名:John123和密码:UDX6672ddM,我想要回应一些东西。如何检查是否用户名和密码匹配?

1 个答案:

答案 0 :(得分:2)

$user = "John123";
$password = "UDX6672ddM";

foreach ($login as $key => $value) {
    if ($key == $user) {
        if ($loginArray[$user] == $password) {
            // user and password match
        }
    }
}

这是对数组中的键而不是值的迭代,这是箭头语法的用法。但为什么你需要使用foreach?如果他们的详细信息在没有循环的数组中,为什么不直接检查每个用户? EG:

$user = "John123";
$password = "UDX6672ddM";

if (array_key_exists($user, $login)) {
    if ($login[$user] == $password) {
        // user and password match
    } else {
        // user exists but password is wrong
    }
} else {
    // user doesn't exist
}