Reputation: 3985
I have an associative array that holds the settings of my object. I also have a function that allows the user to override these setting by passing an associative array of replacement settings. I can use array_replace() however I don't want any values with unknown associative array keys to be added to the settings.
e.g.
$settings = array(
'colour' => 'red',
'size' => 'big'
);
$settings = array_replace( $settings, array(
'size' => 'small',
'weight' => 'heavy'
) );
I want settings to produce:
Array
(
[colour] => red
[size] => small
)
Instead I get this:
Array
(
[colour] => red
[size] => small
[weight] => heavy
)
Upvotes: 0
Views: 172
Reputation: 69
You could preset what you require in an array and then just grab the values of the new array and just set what you need regardless if there is any more options
function settings($array)
{
return array(
"colour" => $array['colour'],
"size" => $array['size']
)
}
$settings = settings($array);
Upvotes: -2
Reputation: 16573
First you need to filter out unwanted items with array_intersect_key
.
$settings = array(
'colour' => 'red',
'size' => 'big'
);
$new_settings = array(
'size' => 'small',
'weight' => 'heavy'
);
$settings = array_merge($settings, array_intersect_key($new_settings, $settings));
Upvotes: 3