Using PHP array_push() to Append Elements to an Array
This tutorial explains the PHP array_push() function, its syntax, parameter details, and demonstrates how to add single or multiple elements to an array while retrieving the new array length, complete with code examples and expected output.
In PHP programming, arrays are a frequently used data structure, and a quick way to add new elements to the end of an existing array is the array_push() function. This article details how to use array_push() and provides code examples.
The syntax of array_push() is as follows:
array_push(array &$array, mixed $value1, mixed $value2, ...)Parameter description:
&$array: required, the array to which elements will be added.
$value1, $value2, ...: required, one or more elements to append to the array.
Below is a practical example of using array_push() :
<?php
// Create an empty array
$fruits = array();
// Add elements to the array
array_push($fruits, "apple");
array_push($fruits, "banana");
array_push($fruits, "orange");
// Output the array contents
print_r($fruits);
?>Running the above code outputs:
Array
(
[0] => apple
[1] => banana
[2] => orange
)As shown, array_push() sequentially adds "apple", "banana", and "orange" to the end of $fruits , and the output displays the added elements with their indexes.
In addition to adding elements one by one, array_push() also supports adding multiple elements at once:
<?php
$numbers = array(1, 2);
// Add multiple elements
array_push($numbers, 3, 4, 5);
print_r($numbers);
?>Running this code produces:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)Here, several elements are specified in array_push() separated by commas, and they are appended to the array in order.
Note that array_push() returns the new length of the array after the operation. To capture this length, assign the function’s return value to a variable:
<?php
$myArray = array(1, 2);
// Add elements and get the new length
$length = array_push($myArray, "a", "b", "c");
echo "New array length: " . $length;
?>Running the snippet outputs:
New array length: 5In this example, array_push() returns the length of $myArray after adding the new elements, which is stored in $length and then printed.
Summary
array_push() is a convenient PHP function that allows you to quickly add one or more elements to the end of an array; understanding its syntax and return value helps simplify code and improve development efficiency.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.