Using PHP’s array_push() Function: Syntax, Parameters, and Examples
This article explains PHP’s array_push() function, covering its basic syntax, required and optional parameters, return value, and provides clear code examples showing how to add single or multiple elements to an array.
PHP is a highly flexible and powerful server‑side scripting language widely used in web development. Among its extensive function library, array_push() is an important built‑in function that adds one or more values to the end of an array. Below we introduce the detailed usage of array_push() .
1. Basic syntax of array_push()
The basic syntax of array_push() is as follows:
<code>array_push ( array &$array , mixed $value1 [, mixed $... ] ) : int</code>In this syntax there are two parameters: $array and $value1 . $array is required and represents the array to which elements will be added; $value1 and any subsequent arguments are optional values to append, and they can be of any type such as strings, numbers, or objects.
The array_push() function returns the number of elements in the array after the operation, i.e., the total count. Note that the $array parameter must be passed by reference, meaning the array is modified directly rather than being copied.
2. Usage examples of array_push()
Below are concrete examples demonstrating how to use array_push() .
Example 1: Adding a single value to the end of an array
In this example we add a new name to an array called $names .
<code>$names = array('Alice', 'Bob', 'Charlie');
array_push($names, 'David');
print_r($names); // Output: Array ( [0] => Alice [1] => Bob [2] => Charlie [3] => David )</code>First we create the $names array containing three names. Then we call array_push() to append the string ‘David’ to the end of the array. Finally we use print_r() to output $names , confirming that the new element appears at the last position.
Example 2: Adding multiple values to the end of an array
Now we demonstrate adding several values to an array. We will add two new colors to the $colors array.
<code>$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 )</code>In this example the array_push() function adds the elements ‘yellow’ and ‘purple’ to the end of $colors , and print_r() shows the updated array.
Conclusion
The array_push() function is a very useful array operation in PHP, allowing developers to conveniently add new elements to an array. It is frequently needed in real development, and we hope this article helps your work.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.