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?
4
Answers
To solve this is to loop through the outer array and use array_search() to search for the value within each inner array.
array_keys
returns an array of an array’s keys.3V4l
Slight modification to your code to combine the keys and column values:
The problem with seeking "something sexier" for this task is that if "sexier" means a "functional iterator", then that comes a cost of not being able to "return early" (doing unnecessary cycles).
If you want a single-line function to call, you can build your own and put it in a helpers file somewhere in your project. My strong advice is to abandon "sexy" for this task and use a breakable foreach loop.
Code: (Demo)
If you are going to perform repeated searches on the same array and the second column is guaranteed to contain unique values, then you can convert the array into a lookup array without losing any data. (Demo)