Can. Two merging methods: 1. Use the array_push() function to insert another array to the end of the array, the syntax is "array_push(array 1, array 2)"; 2. Use the array_merge_recursive() function to merge one or more arrays Merge into an array. When the same key is encountered, the values in the key will be merged into a sub-array. The syntax is "array_merge_recursive(array1, array2)".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php array merging retains all elements, which is merging When using an array, if the keys are the same, the value of the subsequent array will not overwrite the value of the previous array.
The following introduces two methods of merging PHP arrays to retain all elements.
Method 1: Use array_push() function
array_push() function is used to insert one or more elements to the end of the array
array_push(array,value1,value2...)
Parameters | Description |
---|---|
array | Required. Specifies an array. |
value1 | Required. Specifies the value to add. |
value2 | Optional. Specifies the value to add. |
array_push() function can put a variable into another array. When the variable is an array, an array can be inserted at the end of the array.
<?php header('content-type:text/html;charset=utf-8'); $a = [1,'a'=>'aa',2,'b'=>'bb']; $b = [2,'a'=>'aaa',4,'b'=>'bb']; var_dump($a); var_dump($b); echo "数组合并后:"; array_push($a, $b); var_dump($a); ?>
Method 2: Use the array_merge_recursive() function
array_merge_recursive() function is used to merge one or more arrays into an array.
The difference between this function and the array_merge() function is that it handles the situation where two or more array elements have the same key name. array_merge_recursive() does not perform key name overwriting, but recursively combines multiple values with the same key name into an array.
That is, merge arrays. When encountering the same key, merge the values in the key into a sub-array.
<?php header('content-type:text/html;charset=utf-8'); $a = [1,'2'=>2,'a'=>'a','b'=>'b']; $b = [1,'2'=>3,'a'=>'a','b'=>'d','c'=>'e']; var_dump($a); var_dump($b); echo "数组合并后:"; $c = array_merge_recursive($a,$b); var_dump($c); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Is it possible to combine php arrays to retain all elements?. For more information, please follow other related articles on the PHP Chinese website!