Question

Is there an array function in PHP that somehow does array_merge, comparing the values, ignoring the keys? I think that array_unique(array_merge($a, $b)) works, however I believe there must be a nicer way to do this.

eg.

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

resulting in:

$ab = array(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4);

Please note that I don't care about the keys in $ab, however it would be nice if they were ascending, starting at 0 to count($ab)-1.

Was it helpful?

Solution

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.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top