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');
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With