Backend Development 3 min read

Using PHP array_push to Append Elements to an Array

This article explains how to use PHP's built-in array_push function to append one or multiple elements to the end of an array, provides clear 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 Append Elements to an Array

In PHP, arrays are powerful data structures that can store multiple values of the same type, and the built‑in array_push function allows you to add new elements to the end of an array.

The array_push function accepts the target array as its first argument and one or more elements as subsequent arguments, appends the elements to the array’s end, and returns the new length of the array.

Example of pushing a single element:

$fruits = array("apple", "banana", "orange");
$length = array_push($fruits, "pear");
echo "New array length: " . $length . "\n";
print_r($fruits);

Running this code outputs:

New array length: 4
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
)

You can also push multiple elements at once. The following example adds “yellow” and “green” to a $colors array:

$colors = array("red", "blue");
$length = array_push($colors, "yellow", "green");
echo "New array length: " . $length . "\n";
print_r($colors);

The execution produces:

New array length: 4
Array
(
    [0] => red
    [1] => blue
    [2] => yellow
    [3] => green
)

In summary, array_push provides a simple way to append one or more elements to an array, returning the updated length and allowing easy inspection of the array’s contents.

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

login 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.