0

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

)
7
  • what u expect to get in result Commented Sep 8, 2011 at 8:01
  • 1
    Do you want the keys only or the values for the keys (in which case I assume the value for a given key is going to be the same in both arrays)? Commented Sep 8, 2011 at 8:02
  • 1
    This doesnt clarify it for me. Please give a full example output. Also see + operator for arrays Commented Sep 8, 2011 at 8:04
  • 1
    Also: give the smallest example that explains what you need. There's no need to put 15 elements in each array to illustrate. Commented Sep 8, 2011 at 8:07
  • 1
    please use var_export, not print_r, when dumping arrays :) Commented Sep 8, 2011 at 8:07

4 Answers 4

4
$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().

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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);

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.