Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Merging two arrays into one array (also Remove Duplicates)

People also ask

Does array concat remove duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates.

How do you remove duplicates from an array in place PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.


array_unique(array_merge($array1,$array2), SORT_REGULAR);

http://se2.php.net/manual/en/function.array-unique.php


As already mentioned, array_unique() could be used, but only when dealing with simple data. The objects are not so simple to handle.

When php tries to merge the arrays, it tries to compare the values of the array members. If a member is an object, it cannot get its value and uses the spl hash instead. Read more about spl_object_hash here.

Simply told if you have two objects, instances of the very same class and if one of them is not a reference to the other one - you will end up having two objects, no matter the value of their properties.

To be sure that you don't have any duplicates within the merged array, Imho you should handle the case on your own.

Also if you are going to merge multidimensional arrays, consider using array_merge_recursive() over array_merge().


It will merger two array and remove duplicate

<?php
 $first = 'your first array';
 $second = 'your second array';
 $result = array_merge($first,$second);
 print_r($result);
 $result1= array_unique($result);
 print_r($result1);
 ?>

Try this link link1


try to use the array_unique()

this elminates duplicated data inside the list of your arrays..