0

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
)
2
  • 2
    Why are you merging if you just want to override? Commented Feb 5, 2014 at 22:29
  • Oops I meant array_replace(); Commented Feb 5, 2014 at 22:46

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I'm after
-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.