I have an array where I want to search the uid
and get the key of the array.
Examples
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'
)
);
The function call search_by_uid(100)
(uid of first user) should return 0
.
The function call search_by_uid(40489)
should return 2
.
I tried making loops, but I want a faster executing code.
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:
For multiple results
In case you have an associative array as pointed in the comments you could make it with:
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!
If question i.e.
Ans:
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
Usage:
$results = searcharray('searchvalue', searchkey, $array);
Just share, maybe can like this.
Try this also