PHP
๐ฅ PHP array_push() Function: Appending Elements to Arrays
The array_push() function in PHP pushes one or more elements onto the end of an array. It treats the array as a stack and increases the array length by the number of passed elements.
-
Return Value:
array_push()modifies the target array directly (passed by reference) and returns the total number of elements in the array after the operation.
๐ ๏ธ Basic Syntax & Usage
You can push a single element or multiple values separated by commas in a single function call:
PHP
$fruits = ["Apple", "Banana"];
// Pushing a single element
array_push($fruits, "Cherry");
// Pushing multiple elements at once
array_push($fruits, "Date", "Elderberry");
print_r($fruits);
/*
Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
[3] => Date
[4] => Elderberry
)
*/
โก Performance Tip: array_push() vs. $array[] Syntax
If you only need to add one single element to an array, using the square bracket assignment syntax $array[] = $value is faster because it avoids calling a function overhead.
PHP
$users = ["Alice", "Bob"];
// Recommended for single values (Faster & Cleaner)
$users[] = "Charlie";
// Use array_push() primarily when adding multiple values at once
array_push($users, "David", "Emma");
print_r($users);
๐ Key Rules & Behaviors
-
1. Modification by Reference: The array is passed by reference (
&$array), meaning the original array variable is directly modified. - 2. Numeric Indexing: Newly pushed elements are always assigned auto-incremented numeric integer keys, even if the array previously contained string keys.
-
3. Type Requirement: The first argument must be an array. Passing a non-array variable throws an
ArgumentCountErrororTypeErrorin modern PHP versions.
๐ Method Comparison
| Approach | Syntax | Multiple Values | Performance |
|---|---|---|---|
| Square Brackets | $arr[] = $val; |
No (Single value per call) | Faster (Direct memory allocation) |
| array_push() | array_push($arr, $v1, $v2); |
Yes (Variadic parameters) | Slightly slower (Function call overhead) |
-
๐ Short Summary
-
array_push()adds one or more values onto the end of an array. -
Prefer
$array[] = $valuewhen appending a single element for better execution speed. - The function directly mutates the source array and returns the updated total element count.
