Backend Development 4 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP’s array_push() Function to Append Elements to an Array

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:

The output will be:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

The function also supports adding multiple elements at once:

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:

The above code outputs:

New array length: 5

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

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