Home > Net >  PHP, Get array key by searching in every sub array
PHP, Get array key by searching in every sub array

Time:02-08

I have an array of list of currencies and each currency got an subarray with all countries.

I will receive a country (alpha 2 code) and i need to retrieve the currency associated with my previous array.

$currencies = [
    'EUR' => ['AT', 'BE', 'CY', 'EE', 'FI', 'FR', 'DE', 'GR', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PT', 'ES', 'SI', 'SK'],
    'JPY' => ['JP'],
    'IDR' => ['ID']
];

I can do it with a foreach, but i hope that PHP have a function to automatically do it but i didn't find it.

Someone already do that ?

CodePudding user response:

You could use array_filter to get an array that matches a condition.

$needle = 'AT';

$filtered = array_filter($currencies, function ($haystack) use ($needle) {
    // return in_array($needle, $haystack);
    return isset(array_flip($haystack)[$needle]); // more efficient than in_array
});

$countriesArray = array_keys($filtered); // ['EUR']

Using Collections

$res = collect($currencies)
    ->filter(function ($haystack) use ($needle) {
        return isset(array_flip($haystack)[$needle]);
    })
    ->keys()
    ->all();

Using Collection and short closures

$res = collect($currencies)
    ->filter(fn($haystack) => isset(array_flip($haystack)[$needle]))
    ->keys()
    ->all();
  •  Tags:  
  • Related