In PHP, methods are essential functions within classes or objects, facilitating object-oriented programming, code organization, abstraction, and encapsulation. Understanding methods is crucial for implementing inheritance, polymorphism, and building modular, reusable code. The array_push() is a vital function for convenient and readable array manipulation, widely used in dynamic PHP applications.
In this blog, we will discuss the array_push() in php. Also, we will give you an easy understanding of what the array push() function in PHP is and how it functions.
What is array_push() in PHP?
The array_push() function in php adds new elements to the Array's end and modifies the Array's element count. You are allowed to add as many elements as you want. If the Array has string keys, added elements will still have numeric keys. Because of the addition of new elements, the length of an array will increase by the number of elements pushed.
Syntax of PHP array_push() function
array_push($array, $elm1, $elm2, $elm3....)
Parameters of array_push() in php
Depending on the elements added, the function would take different parameters. Parameters are divided into two parts:
Parameters
Parameter | Type | Description |
---|---|---|
$array | Array | This applies to the Array to which we want to add elements. |
List of elements $elm | Integer, Float, String, Array | Elements that we want to insert into the initial Array |
Return Value of array_push() in php
array_push() function in PHP returns an updated array with new elements pushed into it on end. If the initial array consists of an integer key value, then the function will always add a numeric key to the pushed value.
Examples of PHP array_push()
Basic Example
Output:
Array before push operation: Array([0]=>Hindi[1]=>Maths[2]=>Chemistry[3]=>English)
Array after push operation: Array([0]=>Hindi[1]=>Maths[2]=>Chemistry[3]=>English[4]=>Social Science[5]=>Yoga)
array_push() function in PHP with Integer key Value
Output:
Array before push operation: Array([1]=>Hindi[2]=>Physics[3]=>Chemistry[4]=>English)
Array after push operation: Array([1]=>Hindi[2]=>Physics[3]=>Chemistry[4]=>English[5]=>Dance[6]=>Yoga)
array_push() function in PHP without Integer key Value
Output:
Array before push operation: Array([a]=>India[b]=>USA[c]=>China[d]=>England)
Array after push operation: Array([a]=>India[b]=>USA[c]=>China[d]=>England[0]=>Afghanistan[1]=>Bangladesh)
Push an array inside an array using the array push() function in PHP
Output:
Array before push operation: Array([0]=>India[1]=>China[2]=>USA[3]=>Pakistan)
Array after push operation: Array([0]=>India[1]=>China[2]=>USA[3]=>Pakistan[4]=>Array([0]=>Indonesia[1]=>Canada[2]=>Afghanistan[3]=>Dubai)
Must Read: Laravel Facades