0

Assume we have the following 2-dimensional array:

$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'urlof40489'
    )
);

If I want to search a key I can use (and get 0 in this example):

$key = array_search('100', array_column($userdb, 'uid'));

But what do I use if I want to get the key for two attributes that should match a specific value. Like I want to search for the key that has uid = '100' AND name = 'Sandra Shush' ?

0

2 Answers 2

3

It's probably simplest just to use a foreach over the values e.g. this function will return a similar value to array_search:

function find_user($userdb, $attributes) {
    foreach ($userdb as $key => $user) {
        if (empty(array_diff($attributes, $user))) return $key;
    }
    return false;
}

echo find_user($userdb, array('name' => 'Stefanie Mcmohn', 'uid' => 5465));

Output

1

Demo on 3v4l.org

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

Comments

1

why not loop over the array?

$foundKey = false;
foreach($userdb as $key => $user){
   if($user['uid']=='100' && $user['name '] == 'Sandra Shush'){
        $foundKey = $key;
   }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.