Create a new array from a list of keys in PHP

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 wonder if there is a PHP function there that does this already. Something like the function array_from_keys()below.

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

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

// $chosen = array('small' => '10px', 'large' => '13px');
+5
source share
3 answers

PHP has a built-in function that allows such manipulations, i.e. array_intersect_keyhowever you will have to change your syntax a 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
    );
+9
source

There is no function for this, as far as I know. The easiest way is to do something like this, I think:

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

, , :

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

:

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

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

All Articles