chchrist
chchrist

Reputation: 19842

How to merge these two arrays?

I want to merge those two arrays and get only the unique key values. Is there a php function for this? array_merge() doesn't work.

Array
(
    [1] => 3
    [2] => 4
    [3] => 1


)

Array
(
    [1] => 3
    [2] => 1
    [3] => 2

)

RESULT ARRAY THAT I WANT

Array
(
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4

)

Upvotes: 0

Views: 242

Answers (4)

Kees Schepers
Kees Schepers

Reputation: 2258

Following peice of code gives exact what you wants but the question is do you really want the keys in the result are starting from 1 instead of 0? If you don't Arnaud his option is the best solution.

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

$array2 =  array(
    1 => 3,
    2 => 1,
    3 => 2
);

$values = array_unique(array_merge($array1, $array2));
$keys = array_keys(array_fill_keys($values, ''));
$result = array_combine($keys, $values);
asort($result);

var_dump($result);

Upvotes: 1

Niko
Niko

Reputation: 26730

Try this:

$merged = array_unique(array_merge($array1, $array2));

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

$values = array_unique(array_merge($array1, $array2));
sort($values);

This returns the unique values from array1 and array2 (as per your example).

Try it here: http://codepad.org/CeZewRNT

See array_merge() and array_unique().

Upvotes: 4

Alfwed
Alfwed

Reputation: 3282

$merged = array_unique(array_merge($array1, $array2));

Upvotes: 3

Related Questions