Home Tutorial Php Phpbasics PHP Array Push

 
 

PHP Array Push
Posted on: October 23, 2009 at 12:00 AM
Advertisement
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.

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 )

Advertisement

Related Tags for PHP Array Push:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 23, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com