C
C
chupok2014-09-27 21:04:17
PHP
chupok, 2014-09-27 21:04:17

PHP: How to determine the value of a found key in an array?

Hello!
There is an array:

$arr = array (
  "k1" => "v1",
  "k2" => "v2"
);

It is necessary to find the key and its corresponding value in the array , while the key and value are written to different variables (different variables are not for each pair, but in general, that is, two variables are obtained).
I find the key like this:
$var1 = array_key_exists($login, $arr);
Here $login is a variable into which the data entered by the user is written:
$login = trim($_POST["login"]);
The problem is that I can not determine the value of the found key in any way.
Tried in this way:
$var2 = in_array($password, $arr); // $password - по аналогии с логином

However, the test output via echo returned true , even though a string needs to be output.
I understand that everything is done differently: a database is used, caching-salt, separate files, and much more; But I'm still learning how to ride bikes.
PS: If I explained the situation incorrectly, tell me: I will try to formulate the problem differently.
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
KorsaR-ZN, 2014-09-27
@chupok

The essence of the question is not clear at all, there are few details ...
The array_key_exists and in_array functions check the presence of the desired key or value in the array.
What exactly do you need?
Do you have an array where the key is the username and the value is the password?

$arr = [
'user1' => '123',
'user2' => '124'
];

In general, to find the desired key and its corresponding value:
$login = trim($_POST['login']);

if (isset($users[$login ]) {
   $key = $login;
   $value = $users[$login];
} else {
  echo 'Нет нужного ключа в массиве';
}

R
Roquie, 2014-09-28
@Roquie

$users = [
  'user1' => '123456'
];

// post request ...
$post = array_map('trim', $_POST);
if (isset($users[$post['login']]) && isset($post['password']) && $users[$post['login']] === $post['password'])
{
   //login successful
   $login = $post['login'];
   $password = $users[$post['login']];
}
else
{
   // paste error to session and redirect to ths page. use pattern PRG
   header('Location: http://example.com/redirect_to_this_page');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question