Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new array from key list in PHP

Tags:

arrays

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');
like image 276
bradt Avatar asked Jun 02 '09 05:06

bradt


Video Answer


1 Answers

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
    );
like image 166
Christophe Eblé Avatar answered Sep 19 '22 11:09

Christophe Eblé