PHP array_push() function is “used to insert one or more elements to the end of an array.“
Syntax
array_push(array, value1, value2...)
Parameters
- array: This parameter is required to which we will add the value.
- value1: This parameter is also optional(PHP version 7.3.0+), which is the value we will insert into the specified array.
Return value
Returns the number of elements in the array.
Visual Representation
Example 1: How to Use PHP array_push() function
<?php
$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];
$new = array_push($netflix, 'Shaft');
print_r($netflix);
echo $new."\n";
Output
Array
(
[0] => Stranger Things
[1] => Black Mirror
[2] => Bright
[3] => XOXO
[4] => Shaft
)
5
Example 2: Adding multiple values
<?php
$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];
$new = array_push($netflix, 'Shaft', 'Blue Jay', 'Candy Jar');
print_r($netflix);
echo $new."\n";
Output
Array
(
[0] => Stranger Things
[1] => Black Mirror
[2] => Bright
[3] => XOXO
[4] => Shaft
[5] => Blue Jay
[6] => Candy Jar
)7
In this example, ‘Shaft’, ‘Blue Jay’, and ‘Candy Jar’ are added to the end of the $netflix array.
Example 3: Adding values to the Associative Array
<?php
$data = ['Krunal', 'BE'];
$new = array_push($data, 'Ankit', 'MCA');
print_r($data);
echo $new."\n";
Output
Array
(
[0] => Krunal
[1] => BE
[2] => Ankit
[3] => MCA
)
4
Example 4: Adding an array into an array
<?php
$dataA = ['name' => 'Krunal', 'education' => 'BE'];
$second = ['Facebook', 'Instagram'];
$newA = array_push($dataA, $second);
print_r($dataA);
echo $newA."\n";
Output
Array
(
[name] => Krunal
[education] => BE
[0] => Array
(
[0] => Facebook
[1] => Instagram
)
)
3
Example 5: Pushing key and value in Associative Array
<?php
$data = ['name' => 'Krunal', 'education' => 'BE'];
$data['age'] = 30;
$data['business'] = 'IT';
print_r($data);
Output
Array ( [name] => Krunal [education] => BE [age] => 30 [business] => IT )
Example 6: Append elements using square brackets syntax
If you are using PHP version 5.4 or higher, you can use the square bracket syntax to add elements to an array like this:
<?php
$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];
$netflix[] = 'Shaft';
var_dump($netflix);
Output
array(5) {
[0]=>
string(15) "Stranger Things"
[1]=>
string(12) "Black Mirror"
[2]=>
string(6) "Bright"
[3]=>
string(4) "XOXO"
[4]=>
string(5) "Shaft"
}
goenergia
Thanks u help me.