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.
I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.
Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).
Use of function
Result
Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.
Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.
PHP Fiddle Example
Try this
I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow: