Voting

: three plus three?
(Example: nine)

The Note You're Voting On

drvali at hotmail dot com
15 years ago
<?php
/**
* Merges any number of arrays of any dimensions, the later overwriting
* previous keys, unless the key is numeric, in whitch case, duplicated
* values will not be added.
*
* The arrays to be merged are passed as arguments to the function.
*
* @access public
* @return array Resulting array, once all have been merged
*/
function array_merge_replace_recursive() {
// Holds all the arrays passed
$params = & func_get_args ();

// First array is used as the base, everything else overwrites on it
$return = array_shift ( $params );

// Merge all arrays on the first array
foreach ( $params as $array ) {
foreach (
$array as $key => $value ) {
// Numeric keyed values are added (unless already there)
if (is_numeric ( $key ) && (! in_array ( $value, $return ))) {
if (
is_array ( $value )) {
$return [] = $this->array_merge_replace_recursive ( $return [$$key], $value );
} else {
$return [] = $value;
}

// String keyed values are replaced
} else {
if (isset (
$return [$key] ) && is_array ( $value ) && is_array ( $return [$key] )) {
$return [$key] = $this->array_merge_replace_recursive ( $return [$$key], $value );
} else {
$return [$key] = $value;
}
}
}
}

return
$return;
}

$a = array (
"a" => 1,
"b" => 2,
'foo',
'bar'
);
$b = array (
"a" => 2,
"c" => 3,
'foo'
);

$c = array_merge_replace_recursive ( $a, $b );
print_r ( $a );
print_r ( $b );
print_r ( $c );
?>

Output:
Array
(
[a] => 1
[b] => 2
[0] => foo
[1] => bar
)
Array
(
[a] => 2
[c] => 3
[0] => foo
)
Array
(
[a] => 2
[b] => 2
[0] => foo
[1] => bar
[c] => 3
)

<< Back to user notes page

To Top