Home >Backend Development >PHP Tutorial >How to use array_push function in PHP
In PHP development, array is a very common data structure. In actual development, we often need to add new elements to the array. For this purpose, PHP provides a very convenient function array_push.
The array_push function is used to add one or more elements to the end of the array. The syntax of this function is as follows:
array_push(array,value1,value2,...)
Among them, array is the array to which elements need to be added, and value1, value2, etc. are the elements to be added. There can be one or more elements to add.
Let’s take a look at the specific usage.
To add an element, you can directly pass the element to be added as the second parameter of the array_push function. For example:
$arr = [1,2,3]; array_push($arr,4); print_r($arr);
The output is:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
As you can see, we successfully added an element 4 to the end of the array.
If you want to add multiple elements, you can pass in each element to be added in sequence in the array_push function. For example:
$arr = [1,2,3]; array_push($arr,4,5,6); print_r($arr);
The output result is:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
As you can see, we successfully added multiple elements 4, 5, and 6 to the end of the array.
If you want to add an array to another array, you can use the array_push function combined with the spread operator. For example:
$arr1 = [1,2,3]; $arr2 = [4,5,6]; array_push($arr1, ...$arr2); print_r($arr1);
The output result is:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
As you can see, we successfully added array $arr2 to the end of array $arr1.
Summary
The array_push function is a very convenient function for adding elements to an array in PHP. Its use is very simple, you only need to pass in the elements you want to add. It should be noted that if you want to add multiple elements, you need to pass them in sequentially; if you want to add an array, you need to use the spread operator.
The above is the detailed content of How to use array_push function in PHP. For more information, please follow other related articles on the PHP Chinese website!