Voting

: max(five, zero)?
(Example: nine)

The Note You're Voting On

felix dot ospald at gmx dot de
17 years ago
If you desire correct and performant behaviour (in contrast to the other postings) use this code. It works as documented above.
If you want that keys are always perserved and not appended or renumbered if they are numeric comment out the "if (((string) $key) === ((string) intval($key)))" case.
@spambegone at cratemedia dot com: using empty is not right way to check if an item is in the array use isset!

<?php

function array_merge_recursive2($array1, $array2)
{
$arrays = func_get_args();
$narrays = count($arrays);

// check arguments
// comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
for ($i = 0; $i < $narrays; $i ++) {
if (!
is_array($arrays[$i])) {
// also array_merge_recursive returns nothing in this case
trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
return;
}
}

// the first array is in the output set in every case
$ret = $arrays[0];

// merege $ret with the remaining arrays
for ($i = 1; $i < $narrays; $i ++) {
foreach (
$arrays[$i] as $key => $value) {
if (((string)
$key) === ((string) intval($key))) { // integer or string as integer key - append
$ret[] = $value;
}
else {
// string key - megre
if (is_array($value) && isset($ret[$key])) {
// if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
// in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
$ret[$key] = array_merge_recursive2($ret[$key], $value);
}
else {
$ret[$key] = $value;
}
}
}
}

return
$ret;
}

// Examples:

print_r(array_merge_recursive2(array('A','B','C' => array(1,2,3)), array('D','C' => array(1,4))));
/*
Array
(
[0] => A
[1] => B
[C] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 4
)
[2] => D
)*/

print_r(array_merge_recursive2(array('A','B','0' => array(1,2,3)), array('D','0' => array(1,array(4)))));
/*
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => B
[2] => Array
(
[0] => 1
[1] => Array
(
[0] => 4
)
)
)*/

print_r(array_merge_recursive2(array('A' => array('A' => 1)), array('A' => array('A' => array(2)))));
/*
Warning: Argument #1 is not an array - trying to merge array with scalar! Returning null! in ... on line ...
*/

var_dump(array_merge_recursive2(array('A' => array('A' => 2)), array('A' => array('A' => null))));
/*
array(1) { ["A"]=> array(1) { ["A"]=> NULL } }
*/

?>

<< Back to user notes page

To Top