PHP
Whitelist Specific Keys from an Associative Array
Learn to filter an associative PHP array, keeping only a predefined set of allowed keys and discarding all others, effectively whitelisting desired data for security or trimming.
<?php
/**
* Filters an associative array, keeping only the keys specified in the whitelist.
*
* @param array $array The input associative array.
* @param array $allowedKeys An array of keys to keep (whitelist).
* @return array The filtered array containing only allowed keys.
*/
function whitelist_array_keys(array $array, array $allowedKeys): array
{
// array_flip creates an array where original values become keys.
// array_intersect_key then returns all entries from $array that have keys
// which are present in the flipped $allowedKeys array.
return array_intersect_key($array, array_flip($allowedKeys));
}
// Example usage:
$userData = [
'id' => 1,
'name' => 'Alice',
'email' => '[email protected]',
'password_hash' => 'some_hashed_password',
'api_token' => 'secret_token_123',
'created_at' => '2023-01-01 10:00:00'
];
// Define which keys are safe to expose (whitelist)
$safeKeys = ['id', 'name', 'email', 'created_at'];
$publicUserData = whitelist_array_keys($userData, $safeKeys);
// Expected: ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]', 'created_at' => '2023-01-01 10:00:00']
// 'password_hash' and 'api_token' are removed.
print_r($publicUserData);
// Another example:
$productInfo = [
'product_id' => 'XYZ789',
'name' => 'Premium Widget',
'price' => 29.99,
'description' => 'A very high-quality widget.',
'sku' => 'PW001',
'internal_cost' => 15.00 // Internal data
];
$displayKeys = ['product_id', 'name', 'price', 'description'];
$displayProduct = whitelist_array_keys($productInfo, $displayKeys);
// Expected: ['product_id' => 'XYZ789', 'name' => 'Premium Widget', 'price' => 29.99, 'description' => 'A very high-quality widget.']
print_r($displayProduct);
?>
How it works: This function provides a secure and efficient way to filter an associative array by only keeping a specified set of keys. By using `array_flip` on the list of allowed keys and then `array_intersect_key`, it quickly removes any keys not present in the whitelist. This is invaluable for security (e.g., stripping sensitive data before outputting to a client-side API) or for simply trimming down large arrays to only the necessary fields, improving performance and clarity.