Search in a multi-dimensional array

994 0 0 0

Last Updated : 2024-04-25 17:12:52

If you want to search for a value in a certian column in a multi-dimensional array, consider using one of the following examples.

Here is a sample array structure :


$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'
)
);


Solution#1:
You can use the php built-in function array_search() as follows :


$key = array_search('Value', array_column($array, 'columnName'));
EX:
$key = array_search('100', array_column($users, 'uid'));

Solution #2 : 
Create a function as follows :


function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}

//Function call
$id = searchForId('100', $userdb);

Solution #3:
You can use array_map instead of array_column in the first solution as follows:


$key = array_search('100', array_map(function($v){
return $v['uid'];
},$userdb));

//For case In-sensitive searcg use the following :
$key = array_search(strtolower($searchValue), array_map(function($v){
return strtolower($v['uid']);
},$userdb));



Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .