phparrayskey

Remove blacklist keys from array in PHP


I have an associative array of data and I have an array of keys I would like to remove from that array (while keeping the remaining keys in original order -- not that this is likely to be a constraint).

I am looking for a one liner of php to do this.
I already know how I could loop through the arrays but it seems there should be some array_map with unset or array_filter solution just outside of my grasp.

I have searched around for a bit but found nothing too concise.

To be clear this is the problem to do in one line:

//have this example associative array of data
$data = array(
    'blue'   => 43,
    'red'    => 87,
    'purple' => 130,
    'green'  => 12,
    'yellow' => 31
);

//and this array of keys to remove
$bad_keys = array(
    'purple',
    'yellow'
);

//some one liner here and then $data will only have the keys blue, red, green

Solution

  • $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).