0

What I need is really simple:

I have two arrays like that:

<?php
$a1 = [1,2,3];
$a2 = [2,3,4];

I need to combine them so that the result is:

$result = [1,2,3,4];

I've tried array_merge but the result was [1,2,3,2,3,4]

Daniel
  • 1,229
  • 14
  • 24
lucasvscn
  • 1,210
  • 1
  • 11
  • 16
  • 7
    [array_merge()](http://www.php.net/manual/en/function.array-merge.php), [array_unique()](http://www.php.net/manual/en/function.array-unique.php) and optionally [sort()](http://www.php.net/manual/en/function.sort.php) – Mark Baker Nov 26 '15 at 00:38
  • 1
    Try `print_r(array_unique(array_merge($a1, $a2)));`. Once you merge you need to remove duplicates. – chris85 Nov 26 '15 at 00:40

3 Answers3

1

You can find an answer to this here: Set Theory Union of arrays in PHP

By expanding on your current method. You can call array_unique and sort on the resulting array.

$a = [1,2,3];
$b = [2,3,4];
$result = array_merge($a, $b);
$result = array_unique($result);
sort($result);

This will result in:

array(4) {
    [0] = int(1) 1
    [1] = int(1) 2
    [2] = int(1) 3
    [3] = int(1) 4
}
Community
  • 1
  • 1
Christian
  • 1,557
  • 11
  • 16
0
function merges(/*...*/){
    $args=func_get_args();
    $ret=array();
    foreach($args as $arg){
        foreach($arg as $key=>$v)
        {
            $ret[$key]=$v;
        }
    }
    return $ret;
}

untested, but i guess this would work.. will delete all duplicate keys and return the last key/value pair it found of duplicates

hanshenrik
  • 19,904
  • 4
  • 43
  • 89
0

This might be what you are looking for

$result = $a1 + $a2  //union operation

reference Array Operations

Example

$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
var_dump($c);

Ouput

Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
ashishmohite
  • 1,120
  • 6
  • 14