1

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.

0

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.