How to combine arrays in php so that the second array overwrites the first?

Say I have:

$arr1 = array('green', 'yellow', 'blue', 'red'); $arr2 = array('yellow', black, white, 'red'); 

if I do array_merge($arr1, $arr2,) this gives:

 array(green, yellow, blue, red, yellow, black, white, red); 

I want to make sure that there are no duplicates in the array, note that I do not use array keys, only values.

Is there another simple solution that I am missing?

+4
source share
3 answers
 array_unique( array_merge( $arr1, $arr2 ) ); 
+4
source

For PHP.net there is a function:
http://php.net/manual/en/function.array-unique.php

 $unique_array = array_unique(array_merge($array1, $array2, .... )); 

Also from the documents, note that if you are going to use keys
"Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys"

PRO TIP: Horrible naming, you have to use better names than me.

+2
source

just use array_unique to remove all non-unique values:

 $merged = array_unique(array_merge($arr1, $arr2)); 
+1
source

All Articles