PHP array push
In this tutorial we will discuss about the different techniques to add item into an array.
array_push() is one of the widely used function to add item into an array. General format, parameters it take and type of value it returns is as follows:
| General Format |
int array_push(array &$array, mixed $var [,mixed ..}) |
|
| Parameters |
array &$array: Input array |
mixed $var: Pushed value |
| Return Value |
No of elements in the array |
|
array_push(): It treats array as stack, similar to a stack it pushes the variables at last position (Last In First Out).
Example 1:
<?php
$array
=array("Apple","Ball","Cat");echo
"<b>Initially the values of array is:</b><br/>";print_r(
$array);array_push(
$array,"Dog","Elephant");echo
"<br/><b>After pushing some values,the array become:</b><br/>";print_r(
$array);?>
Output:
Initially the values of array is:
Array ( [0] => Apple [1] => Ball [2] => Cat )
After pushing some values,the array become:
Array ( [0] => Apple [1] => Ball [2] => Cat [3] => Dog [4] =>
Elephant )
Example 2:
<?php
$array
=array("a"=>"Apple","b"=>"Ball","c"=>"Cat");echo "<b>Initially the values of array is:</b><br/>";
print_r($array);
array_push($array,"Dog","Elephant");
echo
"<br/><b>After pushing some values,the array become:</b><br/>";print_r(
$array);?>
Output:
Initially the values of array is:
Array ( [a] => Apple [b] => Ball [c] => Cat )
After pushing some values,the array become:
Array ( [a] => Apple [b] => Ball [c] => Cat [0] => Dog [1] =>
Elephant )
Example 3:
<?php
$array
=array(0=>"Apple",1=>"Ball",2=>"Cat");echo
"<b>Initially the values of array is:</b><br/>";print_r(
$array);array_push(
$array,"Dog","Elephant");echo
"<br/><b>After pushing some values,the array become:</b><br/>";print_r(
$array);?>
Output:
Initially the values of array is:
Array ( [0] => Apple [1] => Ball [2] => Cat )
After pushing some values,the array become:
Array ( [0] => Apple [1] => Ball [2] => Cat [3] => Dog [4] =>
Elephant )
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.