PHP Addition of Array


 

PHP Addition of Array

PHP Addition of Array, in this tutorial you will come to know about how to add two arrays, about foreach loop in short, differences between addition and merging of arrays

PHP Addition of Array, in this tutorial you will come to know about how to add two arrays, about foreach loop in short, differences between addition and merging of arrays

PHP Addition an Array to Another Array

In this PHP beginners tutorial we will study to add an array into another array, don't be confused with array merge and addition of arrays, given example will clear the confusion, in the given example we have used foreach loop, foreach loop is a well known loop construct and almost every modern language supports foreach loop.

PHP 4 has included foreach loop. Foreach loop can be used only on arrays. General format of foreach loop is: 

foreach (array as $var)

In the above format each element of the array is assigned to the variable and inside the loop body we can use that variable.

Example of foreach() Function of PHP Array:

<?php

$var=array("Delhi", "Mumbai","Kolkata");

echo"<b>Before adding elements to the array the values are follows:</b><br/>";

print_r($var);

array_push($var,"Chennai", "Ahmedabad");

echo"<br/><b>After adding elements to the array the values are follows:</b><br/>";

print_r($var);

echo"<br/> <b>Another way to add item into an array is as follows:</b></br>";

$var[5]="Bangalore";

$var[6]="Pune";

print_r($var);

echo"<br/> <b>Another way to add item into an array is as follows:</b></br>";

$var['new']="Gurgaon";

print_r($var);

echo"<br/> <b>Another way to add item into an array is as follows:</b></br>";

$var[]="Jamshedpur";

print_r($var); 

?>

Output:

Jasmine
Rose
Lotus
After adding another array: Array ( [0] => Array ( [0] => Jasmine [1] => Rose [2] => Lotus ) [1] => Array ( [0] => Mango [1] => Apple [2] => Banana ) )
Array ( [0] => Mango [1] => Apple [2] => Banana [3] => Jasmine [4] => Rose [5] => Lotus )

 

Ads