PHP Manipulating an Array Whitelist only some array keys


Example

When you want to allow only certain keys in your arrays, especially when the array comes from request parameters, you can use array_intersect_key together with array_flip.

$parameters = ['foo' => 'bar', 'bar' => 'baz', 'boo' => 'bam'];
$allowedKeys = ['foo', 'bar'];
$filteredParameters = array_intersect_key($parameters, array_flip($allowedKeys));

// $filteredParameters contains ['foo' => 'bar', 'bar' => 'baz]

If the parameters variable doesn't contain any allowed key, then the filteredParameters variable will consist of an empty array.

Since PHP 5.6 you can use array_filter for this task too, passing the ARRAY_FILTER_USE_KEY flag as the third parameter:

$parameters  = ['foo' => 1, 'hello' => 'world'];
$allowedKeys = ['foo', 'bar'];
$filteredParameters = array_filter(
    $parameters,
    function ($key) use ($allowedKeys) {
        return in_array($key, $allowedKeys);
    },
    ARRAY_FILTER_USE_KEY
);

Using array_filter gives the additional flexibility of performing an arbitrary test against the key, e.g. $allowedKeys could contain regex patterns instead of plain strings. It also more explicitly states the intention of the code than array_intersect_key() combined with array_flip().