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:

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

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

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

The output will be:

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

The function also supports adding multiple elements at once:

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

// Add multiple elements
array_push($numbers, 3, 4, 5);

print_r($numbers);
?>

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:

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

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

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

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.

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.

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