Reputation: 28208
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.
Upvotes: 1
Views: 2735
Reputation: 522155
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));
Upvotes: 4
Reputation: 57815
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
)
Upvotes: 5
Reputation: 11583
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?
Upvotes: 2