Adding two arrays by using array_merge

We can add array to an existing array by using array_merge function in PHP. By this two arrays can be joined and one resulting array can be generated.

Here is the syntax
$result = array_merge($array1, $array2);
We will try with an example.
$first=array('a','b','c','d','e','f','g');
$second=array('h','i','j','k');

$result=array_merge($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
The output is here
0 -> a 
1 -> b 
2 -> c 
3 -> d 
4 -> e 
5 -> f 
6 -> g 
7 -> h 
8 -> i 
9 -> j 
10 -> k 
We can preserve the keys of the first array.
$first=array(1=>'First',2=>'Second',3=>'Third');
$second=array(1=>'fourth',2=>'Fifth',3=>'Sixth');

$result=array_merge($first,$second);

while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
The output is here.
0 -> First 
1 -> Second 
2 -> Third 
3 -> fourth 
4 -> Fifth 
5 -> Sixth 

Adding by union of two arrays ( Using operand + )

We can add two arrays by using union command like this .
$result=$first + $second;
If we use this in place of array_merge() ( in above code ) then the output will be like this
1 -> First 
2 -> Second 
3 -> Third 
Let us change the second array and see the result.
$first=array(1=>'First',2=>'Second',3=>'Third');
$second=array(4=>'fourth',5=>'Fifth',6=>'Sixth');

$result=$first + $second;

while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here
1 -> First 
2 -> Second 
3 -> Third 
4 -> fourth 
5 -> Fifth 
6 -> Sixth 
You can read more array Operators.

When to use array_merge and array_push

We will be using array_merge when we want to add one array to an existing array. But to add elements to an existing array we will be using array_push function in PHP

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
Your Rating


Google+

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




Subscribe to our mailing list

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