1

How can I remove duplicate arrays in a multidimensional array?

This is my original array with [1] and [2] being identical.

$array = Array ( [0] => Array ( [0] => Walter [1] => White ) [1] => Array ( [0] => Marie [1] => Schrader ) [2] => Array ( [0] => Marie [1] => Schrader ) [3] => Array ( [0] => Hank [1] => Schrader ) ) 

What I like to achieve:

$array_without_duplicates = Array ( [0] => Array ( [0] => Walter [1] => White ) [1] => Array ( [0] => Marie [1] => Schrader ) [2] => Array ( [0] => Hank [1] => Schrader ) ) 
0

3 Answers 3

3
$results = array(); foreach ($array as $k => $v) { $results[implode($v)] = $v; } $results = array_values($results); print_r($results); 

Demo

If you also want to consider keys when checking for equality, replace implode($v) with serialize($v).

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

Comments

-2
$i=0; foreach($arr as $key=>$val){ $i++; $j=0; foreach($arr as $key2=>$val2){ $j++; if($j<=$i){continue;} if($val===$val2){ unset($arr[$key2]); } } } 

2 Comments

Debug output: Array ( [0] => Array ( [0] => Walter [1] => White ) [1] => Array ( [0] => Marie [1] => Schrader ) [3] => Array ( [0] => Hank [1] => Schrader ) )
Plus: Notice: Undefined offset: 2
-2

You can get rid of duplicates using array_unique with SORT_REGULAR

$array = array_unique($array, SORT_REGULAR); 

2 Comments

works only on unidimensional array
This answer is provably correct and @vishwa's comment is provably incorrect. 3v4l.org/86Dqa This answer's advice is found on the canonical dupe target page.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.