Using PHP's array_push() Function: Syntax, Parameters, Return Value, and Practical Examples

This article explains the PHP array_push() function, covering its syntax, required and optional parameters, return value, reference behavior, and provides step‑by‑step code examples for adding single and multiple elements to arrays.

php Courses
php Courses
php Courses
Using PHP's array_push() Function: Syntax, Parameters, Return Value, and Practical Examples

PHP is a widely used server‑side scripting language, and array_push() is a core built‑in function that appends one or more values to the end of an array.

Basic syntax :

array_push ( array &$array , mixed $value1 [, mixed $... ] ) : int

The first argument $array is passed by reference and must be an existing array; $value1 and any subsequent arguments are optional values of any type that will be added to the array.

The function returns the new total number of elements in the array after the push operation.

Example 1 – Adding a single value :

$names = array('Alice', 'Bob', 'Charlie');
array_push($names, 'David');
print_r($names); // Output: Array ( [0] => Alice [1] => Bob [2] => Charlie [3] => David )

This creates an array $names with three names, then uses array_push() to append "David" as the fourth element, and finally prints the updated array.

Example 2 – Adding multiple values :

$colors = array('red', 'green', 'blue');
array_push($colors, 'yellow', 'purple');
print_r($colors); // Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow [4] => purple )

Here, two new color strings are appended to the $colors array in a single call to array_push().

Conclusion

The array_push() function is a convenient way to add new elements to the end of an array in PHP, returning the updated element count and operating directly on the original array because the array argument is passed by reference.

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.

PHPTutorialarray_pushphp arrays
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.