Remove blacklist keys from array in PHP
$out =
array_diff_key
($data,
array_flip
($bad_keys));
All I did was look through the list of Array functions until I found the one I needed (_diff_key
).
The solution is indeed the one provided by Niet the Dark Absol. I would like to provide another similar solution for anyone who is after similar thing, but this one uses a whitelist instead of a blacklist:
$whitelist = array( 'good_key1', 'good_key2', ... );$output = array_intersect_key( $data, array_flip( $whitelist ) );
Which will preserve keys from $whitelist
array and remove the rest.
This is a blacklisting function I created for associative arrays.
if(!function_exists('array_blacklist_assoc')){ /** * Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays when using their values as keys. * @param array $array1 The array to compare from * @param array $array2 The array to compare against * @return array $array2,... More arrays to compare against */ function array_blacklist_assoc(Array $array1, Array $array2) { if(func_num_args() > 2){ $args = func_get_args(); array_shift($args); $array2 = call_user_func_array('array_merge', $args); } return array_diff_key($array1, array_flip($array2)); }}$sanitized_data = array_blacklist_assoc($data, $bad_keys);