Backend Development 3 min read

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 . "\n";
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 . "\n";
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.

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