How do I combine two arrays without repeating valu

2020-07-03 02:37发布

问题:

I have two arrays:

array('1','2','3','4');
array('4','5','6','7');

Based on them, I'd like to generate an array that contains only unique values:

array('1','2','3','4','5','6','7');

Is there any suitable function for this in PHP?

回答1:

You can use array_merge for this and then array_unique to remove duplicate entries.

$a = array('1','2','3','4');
$b = array('4','5','6','7');

$c = array_merge($a,$b);

var_dump(array_unique($c));

Will result in this:

array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [5]=>
  string(1) "5"
  [6]=>
  string(1) "6"
  [7]=>
  string(1) "7"
}


回答2:

Yes it is array_merge() to remove dups array_unique()

array_unique( array_merge( $array1, array2 ) );


标签: php arrays