1

so im messing around with some php and for some reason in_array() won't pickup if something is within the array, correctly?

index.php:

<form action="login.php" method="get">
    <input name="username" type="text" />
    <input name="password" type="password" />
    <input id="submit" type="submit" />
</form>

login.php:

    <?php
    $username = $_GET["username"];
    $password = $_GET["password"];
        include('data/user_data.php');
        if(in_array($username, $users)):
            echo "in array";
        else: echo "not in array";
        endif;

?>

user_data.php:

<?php $users = array(
dextermb => array("dextermb", "password"),
tonymb => array("tonymb", "password2")
)
?>

When inputting "dextermb" or "tonymb" into username and submitting I get the result "not in array" even though it is in the array?

Thoughts on what might be the issue?

4
  • 3
    You can't use in_array() with a nested array. array_key_exists would work fro you though. Commented Jan 13, 2014 at 12:51
  • 1
    Go with $users = array('dextermb' => 'password1', 'tonymb' => 'password2'); Commented Jan 13, 2014 at 12:52
  • using in_array() in login check in not an optimal solution.... use db call instead of... Commented Jan 13, 2014 at 12:58
  • Hope you're only fiddling with it - please make sure hard-coded username/password pairs won't end up in production ;) Commented Nov 15, 2014 at 23:42

2 Answers 2

4

If this is your users array:

$users = array(
    'dextermb' => array("dextermb", "password"),
    'tonymb' => array("tonymb", "password2")
);

Then you want to simply do:

if(isset($users[$username])) {

Or alternatively:

if(array_key_exists($username, $users)) {

The username is the key in your $users array, the in_array method looks for values (and not nested values).

Sign up to request clarification or add additional context in comments.

4 Comments

Ah nice! Thats a nice way of doing it, probably would be easier to search the array using isset, rather than array_key_exists? *for example matching the password with the name?
@Night That seems simplest to me, yeah
As the password is always going to be the second position in the array, wouldn't you be able to search it by something like "$users[$username,2]" (I know my example doesn't work)
@Night $users[$username][1] would get the password for that user
0

Simply You can use a php built in function

     if(array_key_exists($username, $users)){
     echo "in array";
     }else{
          echo "not in array";
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.