PHP

Whitelist Specific Keys in an Associative Array

Learn to filter an associative array in PHP to retain only a predefined set of keys, effectively whitelisting data fields for security or display.

<?php
function filter_array_by_keys(array $data, array $allowedKeys): array
{
    return array_intersect_key($data, array_flip($allowedKeys));
}

$userProfile = [
    'id' => 123,
    'name' => 'Jane Doe',
    'email' => '[email protected]',
    'password_hash' => 'some_secret_hash',
    'last_login' => '2023-10-26 10:00:00',
    'role' => 'admin'
];

$publicProfileKeys = ['name', 'email', 'last_login'];
$publicProfile = filter_array_by_keys($userProfile, $publicProfileKeys);
print_r($publicProfile);

$adminProfileKeys = ['id', 'name', 'email', 'role'];
$adminProfile = filter_array_by_keys($userProfile, $adminProfileKeys);
print_r($adminProfile);

/*
Expected Output:
Array
(
    [name] => Jane Doe
    [email] => [email protected]
    [last_login] => 2023-10-26 10:00:00
)
Array
(
    [id] => 123
    [name] => Jane Doe
    [email] => [email protected]
    [role] => admin
)
*/
?>
How it works: This function filters an associative array, keeping only the keys specified in an `allowedKeys` array. It uses `array_intersect_key` along with `array_flip` to efficiently create a whitelist. This is crucial for security (e.g., preventing sensitive data leaks) and for preparing data for specific views or APIs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs