I have 2 arrays.Example : $array_1(a,b,c)
and $array_2(a,b,d,e)
I want merge $array_1 and $array_2
.result : $array(a,b,c,d,e)
How to do that ?. Help me !. Thanks u

- 726
- 1
- 10
- 21

- 1
- 3
-
$array=array_unique(array_merge($array_1,$array_2 )); [same question here][1] [1]: http://stackoverflow.com/questions/10572546/php-merge-arrays-with-only-not-duplicated-values – Rusiru Aug 12 '14 at 05:00
-
array_merge() will not remove duplicate entries.... [This link will help you to get rid of duplicate entries][1] [1]: http://stackoverflow.com/a/19088822/2667666 – IamManish Aug 12 '14 at 05:06
7 Answers
Only array_merge itself is not the answer to what you are looking for. After merging the arrays this question expects the duplicates to be removed (as shown in your expected output). Hence it would be
$a=array('a','b','c');
$b=array('a','d','e');
print_r(array_unique(array_merge($a,$b)));

- 46,730
- 8
- 72
- 95
you can use array_merge & array_unique
$array_1 = array('a','b','c');
$array_2 = array('a','b','d','e');
$array = array_unique(array_merge($array_1, $array_2));
print_r($array);
you will get output as you want after print_r
Array ( [0] => a [1] => b [2] => c [5] => d [6] => e )
or in php array
array('a','b','c','d','e');

- 111
- 5
You can use array_merge(array1, array2)
or using unary + operator
for eg:
1. using + operator:
$array_1[0]=a;
$array_1[1]=;
$array_1[2]=c;
$array_2[0]=a;
$array_2[1]=b;
$array_2[3]=d;
$array_2[4]=e;
$arr_new=$array_1+$array_2;
then print the $arr_new
2.using function
$array_1=array("a","b","c");
$array_2=array("a","b","d","e");
print(array_merge($array_1,$array_2));

- 11
- 1
Using array_merge
function
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);

- 22,001
- 7
- 73
- 74
You could also use the array union depending on the circumstances:
The program with two arrays can be merged using this code
<?php
$array1= array("green","red");
$array2= array("blue","yellow");
print_r(array_merge($array1,$array2));
?>
Output will be: Array([0]=>green[1]=>red[2]=>blue[3]=>yellow)
or use array_interlace()
<?php
$a=("a","b","c");
$b=("d","e","f");
print_r(array_interlace($a,$b));
?>
output will be: Array( [0]=>a[1]=>d[2]=>b[3]=>e[4]=>c[5]=>f)

- 1,206
- 5
- 18
- 28