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.

php Courses
php Courses
php Courses
Using PHP array_push to Add Elements to an Array

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 . "
";
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 . "
";
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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPTutorialArraysarray_push
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.