How to Use PHP’s array_push() Function to Append Elements to an Array
This article explains the syntax and usage of PHP’s array_push() function, demonstrates how to add single or multiple elements to an array, shows how to retrieve the new array length, and provides complete code examples with expected output.
In PHP programming, arrays are commonly used, and adding elements to the end of an existing array can be done quickly with the array_push() function.
The syntax of array_push() is:
array_push(array &$array, mixed $value1, mixed $value2, ...)Parameters:
&$array: the array to which elements will be added (required).
$value1, $value2, ...: one or more elements to append (required).
Example of adding single elements:
<?php
// Create an empty array
$fruits = array();
// Add elements
array_push($fruits, "apple");
array_push($fruits, "banana");
array_push($fruits, "orange");
// Output array
print_r($fruits);
?>The output will be:
Array
(
[0] => apple
[1] => banana
[2] => orange
)The function also supports adding multiple elements at once:
<?php
$numbers = array(1, 2);
// Add multiple elements
array_push($numbers, 3, 4, 5);
print_r($numbers);
?>The resulting output is:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)Note that array_push() returns the new length of the array after insertion, which can be captured in a variable:
<?php
$myArray = array(1, 2);
// Add elements and get new length
$length = array_push($myArray, "a", "b", "c");
echo "New array length: " . $length;
?>The above code outputs:
New array length: 5In summary, array_push() is a convenient PHP function for quickly appending one or more elements to the end of an array, helping to simplify code and improve development efficiency.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
