Backend Development 4 min read

Using array_push() to Append Elements to PHP Arrays

This article explains how the PHP array_push() function works, covering its syntax, parameters, return value, and providing clear code examples that demonstrate adding single or multiple elements to an array and retrieving the new array length.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using array_push() to Append Elements to PHP Arrays

In PHP programming, arrays are a fundamental data structure, and adding new elements to the end of an existing array can be done quickly with the array_push() function. This article details the usage of array_push() and provides practical code examples.

The syntax of array_push() is:

array_push(array &$array, mixed $value1, mixed $value2, ...)

Parameter description:

&$array : required, the array to which elements will be added.

$value1, $value2, ... : required, one or more values to append to the array.

Example 1 – adding elements one by one:

<?php
// Create an empty array
$fruits = array();

// Add elements to the array
array_push($fruits, "apple");
array_push($fruits, "banana");
array_push($fruits, "orange");

// Output the array contents
print_r($fruits);
?>

Running the above code outputs:

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

Example 2 – adding multiple elements at once:

<?php
$numbers = array(1, 2);

// Add several elements in a single call
array_push($numbers, 3, 4, 5);

print_r($numbers);
?>

The result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Note that array_push() returns the new length of the array after the elements are added. You can capture this return value as shown below:

<?php
$myArray = array(1, 2);

// Add elements and get the new length
$length = array_push($myArray, "a", "b", "c");

echo "New array length: " . $length;
?>

This script outputs:

New array length: 5

In summary, array_push() is a convenient PHP function that allows you to quickly append one or more elements to the end of an array, returning the updated array length, which helps simplify code and improve development efficiency.

Backendarrayarray_pushphp tutorial
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.