0

Is there a better way to achieve the following:

array_unique(array_merge($array_one, $array_two))

That is, merge two arrays and only have unique values.

array_merge seems to merge uniquely for keys, but i need unique values and can not see a built in function that does this.

I understand 'better' may be subjective. Im thinking purely in the fact that im using two array functions wraped to get the values.

6
  • 1
    These are numeric arrays or associative? Commented Jan 31, 2014 at 23:03
  • array_merge does the right thing with numeric arrays, it just appends them. Commented Jan 31, 2014 at 23:04
  • yes, but i want only unique array values Commented Jan 31, 2014 at 23:07
  • array_unique does that. Commented Jan 31, 2014 at 23:07
  • There's nothing built-in that does this, AFAIK. You could write your own function to do it. Commented Jan 31, 2014 at 23:09

1 Answer 1

0

Not sure you can do it in one fail swoop - two functions isn't bad though .. the only other suggestion is to slip in a condition when forming the second array ($array_two - or the last array formed), e.g.

for($i=0; $i<10; $i++) {
   $array_one[] = $i;
}

for($k=5; $k<15; $k++) {
   if(!in_array($k,$array_one)) $array_two[] = $k;
}

Although of course if the first array isn't fully formed (finished) before the second array begins then this won't help. And if it takes too much delving to do this I would consider keeping the original - as long as it does what you want_g

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.