Whitelist only some array keys

suggest change

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().

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Arrays:
* Arrays
* Whitelist only some array keys

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR