We can add array ( one or more ) 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.
$result = array_merge($array1, $array2,...);
We will try with an example.
Example with two arrays
$first=array('a','b','c','d','e');
$second=array('f','g','h');
$result=array_merge($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
5 -> f
6 -> g
7 -> h
With some common elements
$first=array('a','b','c','d','e');
$second=array('h','d','b','f'); //with some common elements
$result=array_merge($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}
Output is here
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
5 -> h
6 -> d
7 -> b
8 -> f
With numeric keys
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
Keys are renumbered and incremented starting from 0.
associative array with literal keys
$first=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple');
$second=array('new_fruit1'=> 'Strawberry','new_fruit2'=>'Grapes');
$result=array_merge($first,$second);
while (list ($key, $val) = each ($result)) {
echo "$key -> $val <br>";
}