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.
Looks array_filter will be suitable solution for this...
PHP Code
In later versions of PHP (>= 5.5.0) you can use this one-liner:
I modified one of examples below description function array_search. Function
searchItemsByKey
return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:Function code:
Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:
For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"
Here is one liner for the same,
This will work. You should call it like this:
It is important to know that if you are using
===
operator compared types have to be exactly same, in this example you have to searchstring
or just use==
instead===
.Based on angoru answer. In later versions of PHP (
>= 5.5.0
) you can use one-liner.Here is documentation: http://php.net/manual/en/function.array-column.php.