Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_merge & array_unique

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.

like image 260
ptmr.io Avatar asked Jan 11 '11 17:01

ptmr.io


People also ask

What does the array_merge () function do?

The array_merge() function merges one or more arrays into one array. Tip: You can assign one array to the function, or as many as you like. Note: If two or more array elements have the same key, the last one overrides the others.

What is the difference between array_merge () and Array_merge_recursive () in PHP?

Definition and Usage The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How do you use implode?

The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.


1 Answers

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.

like image 97
orrd Avatar answered Sep 29 '22 13:09

orrd