Priska Aprilia Priska Aprilia - 2 months ago 42
PHP Question

PHP multidimensional array search key by value

For example a multidimensional

array
like an example below

$arr = array(

[H1] => array(
"name" => "A"
"title" => "T1"
)
[H2] => array(
"name" => "B"
"title" => "B1"
)
)


Let's say I would like to search
name
which equals to
A
in
$arr
and if it's matched, the searching should return the key which is
H1


How can I do that in php ?

I tried
array_keys($arr, "A")
but it returns me with an array instead of the key.

Answer

This may help -

$arr = array(

 'H1' => array(
            "name" => "A",
            "title" => "T1",
      ),
 'H2' => array(
           "name" => "B",
           "title" => "B1",
      )
);

// Generate a new array with 'keys' and values in 'name'
$new = array_combine(array_keys($arr), array_column($arr, 'name'));

// Search in that new array
$search = array_search('A', $new);

var_dump($search);

Output

string(2) "H1"

Demo

Another simple way would be -

$serach= false;
foreach($arr as $key => $val) {
   if($val['name'] == 'A') {
       $search= $key;
       break;
   }
}
var_dump($search);
Comments