Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array search by value

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.

like image 731
Rachit Avatar asked Jul 12 '11 08:07

Rachit


People also ask

How do you search a multidimensional array?

Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.

How do you find a specific value in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you check if a value is in an array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

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.

like image 176
Jakub Truneček Avatar answered Oct 02 '22 21:10

Jakub Truneček