tags:

views:

99

answers:

3

Hi,

I've got an array, indexed by keys, eg:

array(
    'key1' => 'value1',
    'key2' => 'value2',
    ...
    'key57' => 'value57'
)

How to "filter" that array, in order to only have, for example:

array(
    'key2' => 'value2',
    'key57' => 'value57'
)

and preserve keys.

I know array_filter() function, but I do NOT want to EXCLUDE all items except 2 and 57, no I just want to KEEP these values.

Is there exist a PHP core function we could name array_keep() or something ?

Thanks.

+1  A: 

Well, array_filter leaves out elements for which the callback returns false. You will get your desired result if you reverse the check/logic in your callback function, no?

Anti Veeranna
+2  A: 

If you know exactly which keys you want to keep, you could easily write a function to do that:

<?php 
function array_keep($array, $keys) {
    return array_intersect_key($array, array_fill_keys($keys, null));
}

$array = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key57' => 'value57'
);

$newArray = array_keep($array, array('key2', 'key57'));

print_r($newArray);

Output:

Array
(
    [key2] => value2
    [key57] => value57
)
Tom Haigh
Great, exactly what I wanted, thanks a lot!
abernier
A: 

An alternative to Tom's function:

$keptValues = array_intersect_key($array, array_flip(array($key1, $key2)));

Or, with less magic but more verbose:

$keptValues = array_intersect_key($array, array($key1 => null, $key2 => null));
deceze
Yeah, I used to use array_flip for this but then i discovered array_fill_keys() last week, which I thought might be better
Tom Haigh