In PHP, we usually use arrays to store and operate a set of data, and sometimes we need to combine multiple arrays into one array. This article will explain how to merge one array with another array and how to add elements to the original array.
1. Merge arrays
In PHP, you can use the array_merge() function to merge two or more arrays into one array. The syntax of the function is as follows:
array array_merge ( array $array1 [, array $... ] )
Among them, $array1 represents the first array to be merged, and the following $... represents more arrays to be merged.
The following is an example of merging two arrays $array1 and $array2 into one array:
$array1 = array('a', 'b', 'c'); $array2 = array('d', 'e', 'f'); $result = array_merge($array1, $array2); print_r($result);
Run the above code, the output is as follows:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
We can see After merging $array1 and $array2, we get a new array containing all elements.
It should be noted that when using the array_merge() function to merge arrays, if there are the same key names in the arrays, the later arrays will overwrite the previous arrays.
2. Adding elements to the original array
In PHP, you can use the array_push() function to add one or more elements to the end of the array. The syntax of the function is as follows:
int array_push ( array &$array , mixed $value1 [, mixed $... ]] )
Among them, $array represents the array to which elements are to be added, $value1 to $... represents the elements to be added, which can be one or more.
The following is an example, adding element 'd' to the array $array1:
$array1 = array('a', 'b', 'c'); array_push($array1, 'd'); print_r($array1);
Run the above code, the output is as follows:
Array ( [0] => a [1] => b [2] => c [3] => d )
We can see that A new element 'd' has been added to $array1.
It should be noted that the array_push() function can add multiple elements to the array at one time, and multiple elements can be placed in an array and passed to the function.
In addition to using the array_push() function, you can also add elements to the array in the following ways:
$array1 = array('a', 'b', 'c'); $array1[3] = 'd'; print_r($array1);
Run the above code, the output result is the same as in the previous example.
$array1 = array('a', 'b', 'c'); array_unshift($array1, 'd'); print_r($array1);
Run the above code, the output is as follows:
Array ( [0] => d [1] => a [2] => b [3] => c )
We can see that a new element 'd' is added to $array1 and it becomes the first element of the array.
Summary
This article introduces how to merge multiple arrays into one array and several ways to add elements to the original array. In actual development, these operations are very common and relatively simple and easy to understand. Hope this helps PHP beginners.
The above is the detailed content of Add array to original array in php. For more information, please follow other related articles on the PHP Chinese website!