PHP multidimensional array search by value
If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.
If you want just one result:
$key = array_search(40489, array_column($userdb, 'uid'));
For multiple results
$keys = array_keys(array_column($userdb, 'uid'), 40489);
In case you have an associative array as pointed in the comments you could make it with:
$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!
Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchForId('100', $userdb);
It is important to know that if you are using ===
operator compared types have to be exactly same, in this example you have to search string
or just use ==
instead ===
.
Based on angoru answer. In later versions of PHP (>= 5.5.0
) you can use one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
In later versions of PHP (>= 5.5.0) you can use this one-liner:
$key = array_search('100', array_column($userdb, 'uid'));