0

I'm having some strange issue with array_merge.

The 2 arrays I have are as follows;

$original = array(
    'details' => array('error' => 0)
    'maxWidth' => 700,
    'maxHeight' => 700,
    'size' => 'original'
);

$defaults = array(
    'details' => array(),
    'maxWidth' => 1024,
    'maxHeight' => 1024,
    'size' => 'original'
);

But when i do

$merge = array_merge($defaults, $original);

It doesn't replace the maxWidth and maxHeight with the updated values of 1024, it keeps them at 700

Any idea how i can fix this up?

CodeSauce
  • 255
  • 3
  • 19
  • 39

1 Answers1

1

From the documentation (emphasis by me):

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

So currently you start with the values of $defaults and override with $original. Simply switch your arrays:

$merge = array_merge($original, $defaults);
Marvin
  • 13,325
  • 3
  • 51
  • 57
  • That kills the details in the 'details' part though – CodeSauce Dec 15 '19 at 23:55
  • Yes, that's how that function works. If you want to keep your details, do not include them in `$defaults`. – Marvin Dec 15 '19 at 23:57
  • You could also play around with `array_replace_recursive` or `array_merge_recursive`. See [this answer](https://stackoverflow.com/a/34367698/4616087) for a short overview. – Marvin Dec 15 '19 at 23:59