Using PHP array_push to Add Elements to an Array

This article explains how the PHP array_push function can append one or multiple elements to the end of an array, demonstrates its usage with clear code examples, and shows the resulting array and length output for both single and multiple element insertions.

php Courses
php Courses
php Courses
Using PHP array_push to Add Elements to an Array

In PHP, arrays are a powerful data structure for storing multiple values of the same type, and the built-in array_push function provides a convenient way 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 to be appended as subsequent arguments, returning the new length of the array after insertion.

Example of adding a single element:

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

Running this code outputs a length of 4 and shows the array now contains "apple", "banana", "orange", and "pear".

Example of adding multiple elements at once:

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

This second example also results in a length of 4, with the array now holding "red", "blue", "yellow", and "green".

In summary, the PHP array_push function offers a simple and efficient method for appending one or several elements to an array, helping developers manage array data more flexibly and improve code readability.

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.

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