Ben West
Ben West

Reputation: 680

In PHP, Is there a way to get a subset of an array whose keys match the values in another array?

Currently, I am using this function get indicies to collect the key/values from an array for an array of keys stored as values in another array:

function get_indicies($haystack,$needle_names = array()){

    $needles = array();
    foreach($needle_names as $needle_name){ 
        if( isset($haystack[$needle_name]) ) $needles[$needle_name] = $haystack[$needle_name];
    }
    return $needles;
}

There are a ton of array functions in php, is there a way that I can, in class-scope, do this more efficiently, and user more of the built-in php functions?

Upvotes: 4

Views: 1245

Answers (1)

deceze
deceze

Reputation: 522442

$subset = array_intersect_key($haystack, array_flip($needleNames));

This is often used under the name pluck or similar as helper function.

function pluck(array $array, $keys) {
    if (!is_array($keys)) {
        $keys = func_get_args();
        array_shift($keys);
    }
    return array_intersect_key($array, array_flip($keys));
}

var_dump(pluck($array, array('foo', 'bar', 'baz')));
var_dump(pluck($array, 'foo', 'bar', 'baz'));

Upvotes: 4

Related Questions