array_merge & array_unique

爱⌒轻易说出口 提交于 2019-11-29 10:14:01

The most elegant, simple, and efficient solution is the one mentioned in the original question...

$ab = array_unique(array_merge($a, $b));

This answer was also previously mentioned in comments by Ben Lee and doublejosh, but I'm posting it here as an actual answer for the benefit of other people who find this question and want to know what the best solution is without reading all the comments on this page.

Oliver A.
function umerge($arrays){
 $result = array();
 foreach($arrays as $array){
  $array = (array) $array;
  foreach($array as $value){
   if(array_search($value,$result)===false)$result[]=$value;
  }
 }
 return $result;
}

To answer the question as asked, for a general solution that also works with associative arrays while preserving keys, I believe that you will find this solution most satisfactory:

/**
 * array_merge_unique - return an array of unique values,
 * composed of merging one or more argument array(s).
 *
 * As with array_merge, later keys overwrite earlier keys.
 * Unlike array_merge, however, this rule applies equally to
 * numeric keys, but does not necessarily preserve the original
 * numeric keys.
 */
function array_merge_unique(array $array1 /* [, array $...] */) {
  $result = array_flip(array_flip($array1));
  foreach (array_slice(func_get_args(),1) as $arg) { 
    $result = 
      array_flip(
        array_flip(
          array_merge($result,$arg)));
  } 
  return $result;
}

array_merge will ignore numeric keys, so in your example array_merge($a, $b) would give you $ab, there is no need to call array_unique().

if you have string keys (i.e. an associative array) use array_values() first:

array_merge(array_values($a), array_values($b));
$a = array(0 => 0, 1 => 1, 2 => 2);
$b = array(0 => 2, 1 => 3, 2 => 4);

//add any from b to a that do not exist in a
foreach($b as $item){


    if(!in_array($item,$b)){
        $a[] = $item
    }

}

//sort the array
sort($a);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!