bradt
bradt

Reputation: 531

Create new array from key list 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'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');

Upvotes: 5

Views: 9144

Answers (3)

Christophe Eblé
Christophe Eblé

Reputation: 8161

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

Upvotes: 9

Tom Haigh
Tom Haigh

Reputation: 57805

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

Upvotes: 6

Jeremy L
Jeremy L

Reputation: 7797

Simple approach:

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

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

Upvotes: 1

Related Questions