Home >Backend Development >PHP Problem >How to append elements after array in php
In PHP, appending elements to an existing array is a common requirement in many scenarios. This requirement can be achieved through the array operation functions provided by PHP. This article will introduce several methods of appending to arrays.
array_push()
Function array_push()
The function is a way to add array elements in PHP. This function can be used to add one or more elements to the end of an array, a process also known as push.
array_push()
The syntax of the function is as follows:
array_push($array, $value1, $value2, $value3, ......);
where $array
is the array to which elements are to be added, followed by $value1
, $value2
, $value3
, ... are the values to be added to the array $array
.
Sample code:
$my_array = array("apple", "banana", "orange"); // 在数组的末尾添加一个元素 array_push($my_array, "grape"); // 在数组的末尾添加多个元素 array_push($my_array, "mango", "watermelon"); print_r($my_array);
Output:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => mango [5] => watermelon )
$array[] = $value
SyntaxPHP also provides Another syntax for adding elements after an array is $array[] = $value
. This method does not require calling any functions. It directly adds an empty []
to the array, and then fills the added elements in []
.
Sample code:
$my_array = array("apple", "banana", "orange"); // 添加一个元素 $my_array[] = "grape"; // 添加多个元素 $my_array[] = "mango"; $my_array[] = "watermelon"; print_r($my_array);
Output:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => mango [5] => watermelon )
array_push()
with variadic arguments After PHP 5.6 version , variable-length arguments were introduced into functions. Using variadic parameters allows a function to accept an indefinite number of parameters. When adding elements after the array, you can also use variable parameters, as shown below:
function add_to_array(&$array, ...$values) { foreach ($values as $value) { array_push($array, $value); } } $my_array = array("apple", "banana", "orange"); add_to_array($my_array, "grape", "mango", "watermelon"); print_r($my_array);
Output:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => mango [5] => watermelon )
A add_to_array()
function is defined here , use variable parameters $values
to accept multiple elements to be added. The function loops through $values
and calls the array_push()
function to add elements to the $array
array.
The above are several ways to append elements after an array in PHP. Using array_push()
is the simplest way, while using the $array[] = $value
syntax is more concise. Using variable parameters is suitable for adding multiple elements to a function. Just choose the appropriate method according to the actual situation.
The above is the detailed content of How to append elements after array in php. For more information, please follow other related articles on the PHP Chinese website!