0

I have an array looking like this:

$user = array();
$user['albert']['email'] = '[email protected]';
$user['albert']['someId'] = 'foo1';
$user['berta']['email'] = '[email protected]';
$user['berta']['someId'] = 'bar2';

Now I want to find out which user has a certain someId. In this example I want to know who has the someId bar2 and want the result berta. Is there a decent php function for this or would I have to create this on my own?

2
  • 1
    Not answering the question but why not have the id as the key of the array which would allow you to retrieve the data for a given record by simply using the key directly? e.g. $username = $user[$id]['name']. This seems the more logical way to structure your data and how a database is likely to index the records. Commented Aug 14, 2013 at 12:56
  • It's not an id like the pimary key of the user, it's more like the foreign key to something else. I tried to make that clear by naming it someId instead of id, possibly should have picked more concrete names for this example though. Commented Aug 14, 2013 at 13:06

2 Answers 2

2
$id = 'bar2';

$result = array_filter(
  $user,
  function($u) use($id) { return $u['someId'] === $id; }
);

var_dump($result);

Note: this works in PHP 5.3+.
Note 2: there is no reason to use any version below nowadays.

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

3 Comments

@Veseliq true, but we are in 2013 ^^
Unless it's out of your control
Thanks, array_filter() seems to be a great function, a shame I missed it until now. One question: Why are you using === to compare? I know what it means and what the difference to == is, but my PHP days have been some years ago. Is it better (or safer) to always use === instead of == nowadays?
0

Try this function it will return array of the matches.

function search_user($id) {
    $result = new array();
    foreach($user as $name => $user) {
       if ($user['someId'] == 'SOME_ID') {
           $result[] = $user;
       }
    }
    return $result;
}

if you always have one user with same id then you can just return one user, and throw exception otherwise

function search_user($id) {
    $result = new array();
    foreach($user as $name => $user) {
       if ($user['someId'] == 'SOME_ID') {
           $result[] = $user;
       }
    }
    switch (count($result)) {
        case 0: return null;
        case 1: return $result[0];
        default: throw new Exception("More then one user with the same id");
    }
}

2 Comments

Put it in a function and return $name, would better fit his needs :)
@ironcito Updated, I return an array since there can be more then one user with the same ID (just in case).

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.