Skip to content

Instantly share code, notes, and snippets.

@koenhoeijmakers
Last active November 5, 2020 10:48
Show Gist options
  • Save koenhoeijmakers/2396004b71950ab52a9c91f77113f282 to your computer and use it in GitHub Desktop.
Save koenhoeijmakers/2396004b71950ab52a9c91f77113f282 to your computer and use it in GitHub Desktop.
Merges 2 arrays properly
<?php
/*
* Merges two arrays and takes multi-dimensional arrays into account.
*
* @param array $original
* @param array $merging
* @return array
*/
function array_deep_merge(array $original, array $merging): array
{
$array = array_merge($original, $merging);
foreach ($original as $key => $value) {
if (! is_array($value)) {
continue;
}
if (! array_key_exists($key, $merging)) {
continue;
}
if (is_numeric($key)) {
continue;
}
$array[$key] = array_deep_merge($value, $merging[$key]);
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment