tags:

views:

822

answers:

3

I want a quick easy way to copy an array but the ability to specify which keys in the array I want to copy.

I can easily write a function for this, but I'm wondering if there's a PHP function that does this already. Something like the 'array_from_keys' function below.

$sizes = array('small' => '10px', 'medium' => '12px', 'large' => '13px');

$chosen = array_from_keys($sizes, 'small', 'large');

// $chosen = array('small' => '10px', 'large' => '13px');

+1  A: 

Simple approach:

$sizes = array('small' => '10px', 'medium' => '12px', 'large' => '13px');
$chosen = array("small", "large");
$new = array();

foreach ($chosen as $key)
  $new[$key] = $sizes[$key];
Nerdling
+5  A: 

There's a native function in PHP that allows such manipulations (array_intersect_key), however you will have to modify your syntax a little bit.

    $sizes = array('small' => '10px', 'medium' => '12px', 'large' => '13px');
    $selected = array('small' => null,'large' => null);

    $result = array_intersect_key($sizes, $selected);

    // $result will contain:
    Array
    (
        [small] => 10px
        [large] => 13px
    )
SleepyCod
Thanks for that.A slightly better way to build the array:$selected = array_fill_keys('small', 'large', null);Although it's still not very elegant. Still worth writing that 'array_from_keys' function I think.
bradt
+1  A: 

There isn't a function for this as far as I know. The easiest way would be to do something like this I think:

$chosen = array_intersect_key($sizes, array_flip(array('small', 'large')));

Or as you say you can easily write a function:

function array_from_keys() {
    $params = func_get_args();
    $array = array_shift($params);
    return array_intersect_key($array, array_flip($params));
}

$chosen = array_from_keys($sizes, 'small', 'large');
Tom Haigh
The first solution you posted was the best one in this whole "thread" :)
Ivan Vučica