PHP数组如何匹配第一个值?

时间:2017-02-26 19:44:17

标签: php arrays login passwords username

我有一个这样的数组:

$user_array = array(
"m" => "m",
"a" => "a"

我试图从数组中获取值以匹配我在html-page上的表单中输入的值(就像一个简单的登录页面)。我有以下php代码:

session_start();
$username = $_GET['uname'];
$password = $_GET['psw'];
$login = '';


foreach($user_array as $key=>$value){
    if(($key == $username) && ($value == $password)){
        $login = "Login success";
    }
    else if(($key != $username) && ($value != $password)){
        $login = "Username and password incorrect";
        }
    else if($key != $username){
        $login = "Username does not exist";
        }
    else if($value != $password){
        $login = "Password is incorrect";
   }
}

但是出了点问题,因为我只能从数组中获取最后一个值(用户名a和密码a)以匹配我输入的值。如果我在我的表单中键入用户名m和密码m,那么php代码告诉我我的用户名和密码错误。有人可以告诉我为什么吗? :)

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为你没有突破你的循环。您将继续覆盖变量$login。显然,$login包含$user_array 始终

中最后一个条目的消息

例如,当您找到匹配项时,您可以break退出循环。

session_start();
$username = $_GET['uname'];
$password = $_GET['psw'];
$login = '';


foreach($user_array as $key=>$value){
    if(($key == $username) && ($value == $password)){
        $login = "Login success";
        break;
    }
    else if(($key != $username) && ($value != $password)){
        $login = "Username and password incorrect";
        }
    else if($key != $username){
        $login = "Username does not exist";
        }
    else if($value != $password){
        $login = "Password is incorrect";
   }
}

提示:以下方法可能更好,而不是遍历整个数组:

// Check if username exists
if(array_key_exists($username)) { 

// Check if password is correct
if($user_array[$username] === $password) {
    $login = 'Login success.';
} else {
    $login = 'Password doesn\'t match.';
}

} else { 
    $login = 'Username doesn\'t exist.';
}