PHP array_push() function
The array_push()
function in PHP is used to add one or more elements to the end of an array. This function modifies the original array and can be particularly useful for managing dynamic lists or stacks (First In, Last Out - FILO).
Syntax:
Parameters:
- $array: The input array to which the values will be added (passed by reference).
- $values: One or more values to be added to the end of the array. You can pass multiple values separated by commas.
Return Value:
- Returns the new number of elements in the array after the values have been added.
Example 1: Adding Single Element
In this example, we demonstrate how to use array_push()
to add a single element to an array.
Output:
Here, the number 4
is added to the end of the array, increasing the count to 4
.
Example 2: Adding Multiple Elements
You can also add multiple elements to the array in a single call to array_push()
.
Output:
In this case, both "orange"
and "grape"
are added to the array.
Example 3: Working with an Empty Array
If you call array_push()
on an empty array, it will simply add the specified elements.
Output:
The element "first"
is added to the initially empty array.
Example 4: Using with Multidimensional Arrays
You can use array_push()
to add an element to a multidimensional array.
Output:
Here, a new associative array ["name" => "Charlie"]
is added to the multidimensional array.
Example 5: Return Value of array_push()
The return value of array_push()
indicates the new size of the array after adding the elements.
Practical Usage:
array_push()
is useful for:- Dynamically managing lists where elements are frequently added.
- Implementing stack data structures (FILO).
- Handling collections of items where the order of insertion is important.
Summary:
array_push($array, $value1, $value2, ...)
adds one or more values to the end of the specified array.- The function modifies the original array and returns the new count of elements in the array.
- It can be used effectively with both simple and multidimensional arrays, making it a versatile tool for managing data collections.