5

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');

3 Answers 3

9

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

 <?php
      $sizes = array('small' => '10px', 'medium' => '12px', 'large' => '13px');
      $selected = array_fill_keys(array('small', 'large'), null); 
      $result = array_intersect_key($sizes, $selected);
 ?>

$result will contain:

    Array (
        [small] => 10px
        [large] => 13px
    );
Sign up to request clarification or add additional context in comments.

1 Comment

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.
6

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');

Comments

1

Simple approach:

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

foreach ($chosen as $key)
  $new[$key] = $sizes[$key];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.