Home >Backend Development >PHP Tutorial >What are the other extension functions for PHP array merging?
PHP provides 3 extension functions for merging arrays: array_merge_recursive() recursively merges arrays, array_replace() overwrites values with the same key name, and array_replace_recursive() recursively overwrites values in arrays.
Other extension functions for PHP array merging
In addition to the array_merge()
function, PHP also provides Other extension functions are used to merge arrays. These functions provide different merging options that can be used to handle more complex situations.
1. array_merge_recursive()
This function recursively merges two or more arrays. Unlike array_merge()
, it does not overwrite existing key names, but merges their subarrays into the final result.
$arr1 = ['a' => 1, 'b' => ['c' => 3, 'd' => 4]]; $arr2 = ['a' => 2, 'b' => ['e' => 5, 'f' => 6]]; $result = array_merge_recursive($arr1, $arr2); var_dump($result);
Output:
array(2) { ["a"]=> int(2) ["b"]=> array(3) { ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) } }
2. array_replace()
This function replaces the same key name in the first array with the second array value. It does not merge the arrays, but overwrites the values in the first array with the values in the second array.
$arr1 = ['a' => 1, 'b' => 2, 'c' => 3]; $arr2 = ['b' => 4, 'd' => 5]; $result = array_replace($arr1, $arr2); var_dump($result);
Output:
array(4) { ["a"]=> int(1) ["b"]=> int(4) ["c"]=> int(3) ["d"]=> int(5) }
3. array_replace_recursive()
This function is similar to array_replace()
, but it is recursive Replace values in an array. This means that the values in the subarray will also be replaced.
$arr1 = ['a' => 1, 'b' => ['c' => 3, 'd' => 4]]; $arr2 = ['b' => ['e' => 5, 'f' => 6]]; $result = array_replace_recursive($arr1, $arr2); var_dump($result);
Output:
array(2) { ["a"]=> int(1) ["b"]=> array(2) { ["e"]=> int(5) ["f"]=> int(6) } }
The above is the detailed content of What are the other extension functions for PHP array merging?. For more information, please follow other related articles on the PHP Chinese website!