array_unique removes duplicates from only flattened one dimensional array. But still it can be used in a multi-dimensional array with a small work-around.
Scenario 1: Remove duplicates from array comparing all keys and values in array
Consider this array:
Array ( [0] => Array ( [id] => 1 [value] => 111 ) [1] => Array ( [id] => 2 [value] => 222 ) [2] => Array ( [id] => 3 [value] => 333 ) [3] => Array ( [id] => 1 [value] => 111 ) )
It can be found that both index 1 and 3 are same. It can removed directly with array_unique
using SORT_REGULAR
print_r(array_unique($array, SORT_REGULAR));
This produces:
Array ( [0] => Array ( [id] => 1 [value] => 111 ) [1] => Array ( [id] => 2 [value] => 222 ) [2] => Array ( [id] => 3 [value] => 333 ) )
Scenario 2: Remove duplicates from array comparing a specific key
Now consider the same array but id
of 3rd index is different:
Array ( [0] => Array ( [id] => 1 [value] => 111 ) [1] => Array ( [id] => 2 [value] => 222 ) [2] => Array ( [id] => 3 [value] => 333 ) [3] => Array ( [id] => 4 [value] => 111 ) )
Now, index 1 and 3 are not same since id
is different. But if you still want to remove duplicated value 111
. You can use like this:
$tempArr = array_unique(array_column($array, 'value')); print_r(array_intersect_key($array, $tempArr));
This produces:
Array ( [0] => Array ( [id] => 1 [value] => 111 ) [1] => Array ( [id] => 2 [value] => 222 ) [2] => Array ( [id] => 3 [value] => 333 ) )
Explanation:
-
array_unique
– works only with single dimensional array. - Hence, convert the multidimensional array to single dimensional with required column only using array_column. Here, with just
value
. This should give array like:Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 111 )
- Now, applying
array_unique
is easy in this that results:Array ( [0] => 111 [1] => 222 [2] => 333 )
- Rebuild the array, from single to multidimensional using the array_intersect_key that computes intersection using keys for comparison which results in the desired array.
Thank’s
LikeLike
Like it
LikeLike
Very elegant solution! Nicely done.
LikeLike
nice
LikeLike
Good tutorial, thanks
LikeLike
Thank you. Some of the suggestions out there on Stackoverflow and elsewhere really smelled of a 1990’s hack.
LikeLike
Hi, it’s is soluction in my search.
Like!
LikeLiked by 1 person
THANK YOU! Brilliantly simple and well written
LikeLike
Good approach, but unfortunately array_column doesn’t keep the array indexes so will not work with associative array
LikeLike