PHP Array Push: This tutorial covers one of the important feature of PHP array section, how to push a value in an array in PHP? PHP has array_push() function to add elements at the end of an array.This tutorial has several examples on array_push() function.
Ads
TutorialsAds
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 )
Advertisements
Posted on: October 23, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles