Skip to content

Simple PHP Function to Whitelist Array Keys

1 min read

A simple little PHP method for returning only the entries within an array that have array keys in a whitelist:-

 * Returns only array entries listed in a whitelist
 * @param array $array original array to operate on
 * @param array $whitelist keys you want to keep
 * @return array
function arrayWhitelist($array, $whitelist) {
	return array_intersect_key(

To use you just need to pass the array you want to operate on and an array of keys that you want to keep (the whitelist):-

$data = array(
	'apple' => 'green', 
	'raspberry' => 'red', 
	'banana' => 'yellow'
$whitelist = array(
print_r(arrayWhitelist($data, $whitelist));

This will output:-

    [apple] => green
    [banana] => yellow
© 2024 Andy Carter