Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove blacklist keys from array in PHP

Tags:

arrays

php

key

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
like image 553
hackartist Avatar asked Jun 14 '12 04:06

hackartist


2 Answers

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

like image 69
Niet the Dark Absol Avatar answered Nov 19 '22 07:11

Niet the Dark Absol


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.

like image 32
Pmpr.ir Avatar answered Nov 19 '22 08:11

Pmpr.ir