DEV Community

YURII DE.
YURII DE.

Posted on

PHP: Array filtering by allowed key list

[👀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

Top comments (0)