PHP array adding elements at the end

array_push ($input_array,'input element')
array_push() to add element at the end of the array
By using array_push() we can add elements ( single or a set of elements ) at the end of the array.
We will first create an array like this

$stack = array (1, 2);
array_push ($stack,3,4,5,6);  // we are adding four more elements to the array
echo count($stack);
This will display total number of elements inside the array , that is 6 here.

Create an array with three elements and then add two more elements to it. Check the keys also.
$input=array(0=>'a',1=>'b',2=>'c');
array_push($input,'d','e','f');
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output of above code is here
0 -> a 
1 -> b 
2 -> c 
3 -> d 
4 -> e 
5 -> f 
Adding 1 to 10 ( or 1 to 100 ) numbers into an array
$input=array();
for($i=1;$i<=10;$i++){
array_push($input,$i);
}
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output is here
0 -> 1 
1 -> 2 
2 -> 3 
3 -> 4 
4 -> 5 
5 -> 6 
6 -> 7 
7 -> 8 
8 -> 9 
9 -> 10 

With Literal Keys

$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
$output=array_push($input, 'Strawberry');
echo $output; // Output is 5 
echo "<br><br>";
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output is here.
5

Fruits1 -> Banana 
Fruits2 -> Mango 
Fruits3 -> Apple 
Fruits4 -> Grapes 
0 -> Strawberry 
Now key of the last element is 0. To add one element with key at the end to an associative array we have to use the code below.
$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
$input=$input + array('New_fruit'=>'Strawberry');
while (list ($key, $val) = each ($input)) {
echo "$key -> $val 
"; }
Output is here
Fruits1 -> Banana 
Fruits2 -> Mango 
Fruits3 -> Apple 
Fruits4 -> Grapes 
New_fruit -> Strawberry 
We have seen how elements are added to an array. But we may require to add two arrays.
Visitors Rating
Your Rating




Google+

Post Comment This is for short comments only. Use the forum for more discussions.




HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2018 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer