Merge em all

There are quite a few functions and methods available:

Cake's Hash::merge() (former Set::merge) | array_merge() (pretty much the same than Cake's am() function) | array_merge_recursive()

They produce different results. So it's good to know when which of those merging methods should be best used. See for yourself.

The two arrays we want to merge:
Array
(
    [root] => Array
        (
            [deep1] => Array
                (
                    [deeper1a] => value1a
                    [deeper2b] => value2b
                )

            [deep2] => Array
                (
                    [0] => deeper1
                    [1] => deeper2
                )

            [deep3] => stringX
        )

)
Array
(
    [root] => Array
        (
            [deep1] => Array
                (
                    [deeper1a] => value1a
                    [deeper3b] => value3b
                )

            [deep2] => Array
                (
                    [0] => deeper1
                    [1] => deeper3
                )

            [deep3] => stringY
        )

)

Notes

  • am() is useful if some arrays can be simple strings. This avoids notices thrown. This is irrevelant when it's clear that the input is an array.
  • array_merge_recursive() is value oriented. It ignores keys and merge-adds values regardless if they already exist.
  • array_merge() is more key oriented. If the same key exists, it will be overwritten.
  • Hash::merge() is somewhere in the middle and behaves a little bit more key oriented while trying to keep values as well.

Send your feedback or bugreport!