Using PHP array_push to Add Elements to an Array
This article explains how the PHP array_push function can append one or multiple elements to the end of an array, shows step‑by‑step code examples for single and multiple element insertion, and demonstrates the resulting array length and contents.
In PHP, arrays are powerful data structures that can store multiple values of the same type. To add new elements to an array, the built‑in function array_push can be used.
The array_push function appends one or more elements to the end of an array, takes the target array as the first argument and the element(s) to push as subsequent arguments, and returns the new length of the array.
Example 1 demonstrates pushing a single element "pear" onto an existing $fruits array containing "apple", "banana", and "orange". The code shows the array definition, the call to array_push , and the output of the new length and array contents.
$fruits = array("apple", "banana", "orange");
$length = array_push($fruits, "pear");
echo "New array length: " . $length . "\n";
print_r($fruits);The output confirms that the array length becomes 4 and the array now includes "pear".
Example 2 shows pushing multiple elements ("yellow" and "green") onto a $colors array that initially contains "red" and "blue". The function returns the new length (4) and the updated array is printed.
$colors = array("red", "blue");
$length = array_push($colors, "yellow", "green");
echo "New array length: " . $length . "\n";
print_r($colors);Both examples illustrate that array_push can efficiently add one or several items to the end of an array, simplifying array manipulation in PHP backend development.
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.