How to Add Array Item in PHP


 

How to Add Array Item in PHP

How to Add Array Item PHP: In this PHP tutorial you will come to know about several techniques to add item into an array. The given PHP example illustrates several techniques. You will also know the format of array_push() function.

How to Add Array Item PHP: In this PHP tutorial you will come to know about several techniques to add item into an array. The given PHP example illustrates several techniques. You will also know the format of array_push() function.

i)    PHP array add item

In this PHP 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:

array_push(): It treats array as stack. Similar to a stack it pushes the variables at last position (Last In First Out). 

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

<?php$var=array("Delhi", "Mumbai","Kolkata");echo"Before adding elements to the array the values are follows:
";print_r($var);array_push($var,"Chennai", "Ahmedabad");echo"
After adding elements to the array the values are follows:
";print_r($var);echo"
 Another way to add item into an array is as follows:";$var[5]="Bangalore";$var[6]="Pune";print_r($var);echo"
 Another way to add item into an array is as follows:";$var['new']="Gurgaon";print_r($var);echo"
 Another way to add item into an array is as follows:";$var[]="Jamshedpur";print_r($var);?>

Output is :

Before adding elements to the array the values are follows:
Array ( [0] => Delhi [1] => Mumbai [2] => Kolkata )
After adding elements to the array the values are follows:
Array ( [0] => Delhi [1] => Mumbai [2] => Kolkata [3] => Chennai [4]=> Ahmedabad )
Another way to add item into an array is as follows:
Array ( [0] => Delhi [1] => Mumbai [2] => Kolkata [3] => Chennai [4]=> Ahmedabad [5] => Bangalore [6] => Pune )
Another way to add item into an array is as follows:
Array ( [0] => Delhi [1] => Mumbai [2] => Kolkata [3] => Chennai [4]=> Ahmedabad [5] => Bangalore [6] => Pune [new] => Gurgaon )
Another way to add item into an array is as follows:
Array ( [0] => Delhi [1] => Mumbai [2] => Kolkata [3] => Chennai [4]=> Ahmedabad [5] => Bangalore [6] => Pune [new] => Gurgaon [7] =>Jamshedpur )

Ads