开发者

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

开发者 https://www.devze.com 2023-03-27 04:09 出处:网络
Say I have: $arr1 = array(\'green\', \'yellow\', \'blue\', \'red\'); $arr2 = array(\'yellow\', black, white, \'red\');

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 ensure tha开发者_JS百科t there are no duplicates in the array, note that I am not using array keys, only values.

Is there another simple solution I am missing?


array_unique( array_merge( $arr1, $arr2 ) );


There is a function for that on PHP.net:
http://php.net/manual/en/function.array-unique.php

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

Also from the docs please 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: Terrible naming, you should use better names than I did


simply use array_unique to remove all non-unique values:

$merged = array_unique(array_merge($arr1, $arr2));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号