There is no need to iterate over an array when you know the key you are looking for. Simply check for the value using the key.
if ( $mergedArrays[$username] == $password ) {
return TRUE;
}
Question
I'm attempting a simple array scenario, partially for practice with arrays.
The code below is simply comparing a username
and password
variable combo to merged arrays.
It works, but I think it can be improved drastically.
<?php
$username = 'demo@demo.com';
$password = '123456';
$allowed_creds1 = array('demo@demo.com'=>'123456');
$allowed_creds2 = array('john@smith.com'=>'654321');
$allowed_creds3 = array('jane@doe.com'=>'124578');
$mergedArrays = array_merge($allowed_creds1, $allowed_creds2, $allowed_creds3);
foreach($mergedArrays as $key => $val){
echo "$key, $val \n";
if($username == $key && $password == $val){
die("Valid Username and Password");
}
}
?>
Ideally I'd like to validate with a true/false return so I can do more.
I've considered placing the foreach
loop inside a custom function that returns a boolean value, but before I start complicating it, I feel I should ask if there's a better way to validate my php variables to the merged arrays.
Solution
There is no need to iterate over an array when you know the key you are looking for. Simply check for the value using the key.
if ( $mergedArrays[$username] == $password ) {
return TRUE;
}
OTHER TIPS
Since you're using the username as the array key, you can simply check for the existence of the key:
if (!empty($mergedArrays[$username]) && $mergedArrays[$username] === $password) {
return true;
}
Note that this makes the username case sensitive (many users may not expect this). Note the strict comparison (===
). When comparing strings in this way, you'll need to avoid numeric casting which can lead to incorrect results. For instance:
echo ('0x04d' == '77'); // returns true
Of course, normally you should be storing and checking this information via hashes/encryption in the database.
Check if there is a key called your $username
and then check if the element with this key has a valid value equal to password:
if (array_key_exists($username , $mergedArrays)) {
if(password==$mergedArrays[$username]) return true;
}