Differences between array_replace and array_merge in PHP

For arrays with string keys, yes these are equivalent, as you mentioned. If you have numeric keys, array_merge() will append them as required, and even re-order them if necessary, whereas array_replace() will overwrite the original values.

For example,

$a = array('a' => 'hello', 'b' => 'world');
$b = array('a' => 'person', 'b' => 'thing', 'c'=>'other', '15'=>'x'); print_r(array_merge($a, $b)); print_r(array_replace($a, $b));

As you can see, array_merge has re-indexed the numeric keys of the array, and both of them simply update string keys.

However, when you have numeric keys, array_merge() will simply not care about keys, and add everything in the order it sees, deleting nothing, whereas array_replace() will, as the name suggests, replace keys with similar (numeric) indices:


$a = array('0'=>'a', '1'=>'c');
$b = array('0'=>'b'); print_r(array_merge($a, $b)); print_r(array_replace($a, $b));

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.125.1. UTC+08:00, 2024-05-12 07:45
浙ICP备14020137号-1 $访客地图$