This is a simple, three line approach.
Short description: If one of the Arguments isn't an Array, first Argument is returned. If an Element is an Array in both Arrays, Arrays are merged recursively, otherwise the element in $ins will overwrite the element in $arr (regardless if key is numeric or not). This also applys to Arrays in $arr, if the Element is scalar in $ins (in difference to the previous approach).
function array_insert($arr,$ins) {
# Loop through all Elements in $ins:
if (is_array($arr) && is_array($ins)) foreach ($ins as $k => $v) {
# Key exists in $arr and both Elemente are Arrays: Merge recursively.
if (isset($arr[$k]) && is_array($v) && is_array($arr[$k])) $arr[$k] = array_insert($arr[$k],$v);
# Place more Conditions here (see below)
# ...
# Otherwise replace Element in $arr with Element in $ins:
else $arr[$k] = $v;
}
# Return merged Arrays:
return($arr);
}
In Addition to felix dot ospald at gmx dot de in my opinion there is no need to compare keys with type-casting, as a key always is changed into an integer if it could be an integer. Just try
$a = array('1'=>'1');
echo gettype(key($a));
It will echo 'integer'. So for having Integer-Keys simply appended instead of replaced, add the Line:
elseif (is_int($k)) $arr[] = $v;
A Condition I used is:
elseif (is_null($v)) unset($arr[$k]);
So a NULL-Value in $ins will unset the correspondig Element in $arr (which is different to setting it to NULL!). This may be another Addition to felix dot ospald at gmx dot de: The absolute correct way to check for a Key existing in an Array is using array_key_exists() (not needed in the current context, as isset() is combined with is_array()). array_key_exists() will return TRUE even if the Value of the Element is NULL.
And the last one: If you want to use this approach for more than 2 Arrays, simply use this:
function array_insert_mult($arr) {
# More than 1 Argument: Append all Arguments.
if (func_num_args() > 1) foreach (array_slice(func_get_args(),1) as $ins) $arr = array_insert($arr,$ins);
# Return merged Arrays:
return($arr);
}
And if you worry about maintaining References: Simply use $ins[$k] instead of $v when assigning a Value/using a Value as Argument.