Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate values from a multi-dimensional array in PHP

How can I remove duplicate values from a multi-dimensional array in PHP?

Example array:

Array (     [0] => Array     (         [0] => abc         [1] => def     )      [1] => Array     (         [0] => ghi         [1] => jkl     )      [2] => Array     (         [0] => mno         [1] => pql     )      [3] => Array     (         [0] => abc         [1] => def     )      [4] => Array     (         [0] => ghi         [1] => jkl     )      [5] => Array     (         [0] => mno         [1] => pql     )  ) 
like image 498
Ian Avatar asked Nov 21 '08 02:11

Ian


People also ask

How do you remove duplicates from an array in 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.

What is multidimensional array in PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.


2 Answers

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

$input = array_map("unserialize", array_unique(array_map("serialize", $input))); 
like image 150
daveilers Avatar answered Sep 21 '22 04:09

daveilers


Since 5.2.9 you can use array_unique() if you use the SORT_REGULAR flag like so:

array_unique($array, SORT_REGULAR); 

This makes the function compare elements for equality as if $a == $b were being used, which is perfect for your case.

Output

Array (     [0] => Array         (             [0] => abc             [1] => def         )      [1] => Array         (             [0] => ghi             [1] => jkl         )      [2] => Array         (             [0] => mno             [1] => pql         )  ) 

Keep in mind, though, that the documentation states:

array_unique() is not intended to work on multi dimensional arrays.

like image 31
Ja͢ck Avatar answered Sep 23 '22 04:09

Ja͢ck