There are many ways to sum (ie merge) two arrays in PHP. Two of the commonly used functions are introduced below.
array_merge() function merges multiple arrays into a new array, and the keys of the new array will be reordered. The syntax of this function is as follows:
array array_merge ( array $array1 [, array $... ] )
Among them, the parameter array1 represents the first array to be merged, and the parameter... represents the second, third, fourth, etc. arrays to be merged, which can always List all arrays that need to be merged. This function returns a merged array.
For example, the following code merges two arrays into a new array:
$arr1 = array('name' => 'Alice', 'age' => 18); $arr2 = array('name' => 'Bob', 'gender' => 'male'); $result = array_merge($arr1, $arr2); print_r($result);
The output result is:
Array ( [name] => Bob [age] => 18 [gender] => male )
As you can see, array $arr2 covers array $ elements in arr1, with new key-value pairs added.
The array_replace() function is similar to the array_merge() function, both of which merge two or more arrays into a new array. The difference is that the array_replace() function overwrites the same key-value pairs in the previous array with the values of the subsequent array. The syntax of this function is as follows:
array array_replace ( array $array1 [, array $... ] )
Among them, the parameter array1 represents the first array to be merged, and the parameter... represents the second, third, fourth, etc. arrays to be merged, which can always List all arrays that need to be merged. This function returns a merged array.
For example, the following code merges two arrays into a new array:
$arr1 = array('name' => 'Alice', 'age' => 18); $arr2 = array('name' => 'Bob', 'gender' => 'male'); $result = array_replace($arr1, $arr2); print_r($result);
The output result is:
Array ( [name] => Bob [age] => 18 [gender] => male )
As you can see, array $arr2 covers array $ The elements in arr1 also retain different key-value pairs.
Summary
array_merge() function merges multiple arrays into a new array, and the key names of the new array will be reordered; the array_replace() function merges multiple arrays into a new array, Overwrite the value of the same key name. Just choose different functions according to your needs.
The above is the detailed content of What is the sum function of two arrays in php. For more information, please follow other related articles on the PHP Chinese website!