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.

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.

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

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.