Search code examples
phparraysmultidimensional-arrayfilteringassociative-array

Get key (not index) from qualifying row in an associative array of associative arrays


Here my array:

$array = [
    'key1' => [
        'first' => 'azerty',
        'second' => 'qwerty'
    ],
    'key2' => [
        'first' => 'hello',
        'second' => 'world'
    ]
];

With the value 'qwerty' I would like to retrieve the 'key1'.

I looking for something like that:

$theKeyIWant = array_search('qwerty', array_column($array, 'second'));

But I get '0', instead of 'key1' (and I know that's how it works)

Anyone know how to adapt this code or know another code to get the key value?


Solution

  • Slight modification to your code to combine the keys and column values:

    $theKeyIWant = array_search('qwerty', array_combine(array_keys($array), array_column($array, 'second')));