PHP: Array filtering by allowed key list

YURII DE. - Jun 16 '22 - - Dev Community

[👀DEMO]

<?php

// PHP Versions and Options (7.3.33)

class Tools
{
    public static function filter_keys_allowed_list(
        array $arr = [],
        array $allowed = []): array
    {
        return array_filter(
            $arr,
            function ($key) use ($allowed) {
                return in_array($key, $allowed);
            },
            ARRAY_FILTER_USE_KEY
        );
    }
}
$arr = [
    'EUR' => '€96.06',
    'GBP' => '£82.42',
    'JPY' => '¥13,287.09',
    'USD' => '$1',
];
$allowed = ['EUR', 'GBP', 'JPY'];

var_dump(Tools::filter_array_keys_list($arr, $allowed));

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .