How would I get a value from two arrays at a specific index? I have a $usernames array, and a $passwords array. I also have variables called $username and $password (which are the username and password user entered).
I want to get the index of $username in $usernames and compare it to the index of $password in $passwords. If they match, username and password are correct. If not, they are not correct.
I know array’s are probably not the best way to do it, but its only for like 5 people and does not really have to be top secret, just a simple password protect.
I have tried:
<?php
$usernames = array("test1", "test2");
$passwords = array("password1", "password2");
$list = array($usernames, $passwords);
if (in_array($userName, $usernames)) {
$userNameIndex = returnIndex($usernames, $userName);
$passWordIndex = returnIndex($passwords, $password);
echo("it says:<br />");
echo($userNameIndex . " and password: " . $passWordIndex);
} else {
echo("Not In Array");
}
?>
<?php
function returnIndex($array, $value) {
$ar = $array;
$searchValue = $value;
for($i=0; $i< count($ar); $i++) {
if($ar[i] == $searchValue) return i;
}
}
?>
However it returns
it says:
and password: i
First of all, you don’t need a
function returnIndexbecause PHP already has one: it’s calledarray_search.You would use it like this:
However: having separate arrays of usernames and passwords, while it does work, is not really the most straightforward approach. It would be better if you have each username and its password “close together”. If the decision is entirely in your hands you could for example use usernames as keys and passwords as values in the same array:
This way you can do it much more easily and without any need for business functions: