Remove Duplicate Entries In A PHP Array

Wednesday, August 6, 2008 - 09:21

Use the following function to remove all duplicate values in an array.

function remove_duplicated_values($array){
 $newArray = array();
 foreach($array as $key=>$val){
  $newArray[$val] = 1;
 return array_keys($newArray);

The way this function works is by looping through the array and assigning each value of the array to be a key of a new array and setting the value as 1. As the values of the array are added to the new array any new values will lengthen the array and any duplicate values will reset to be 1.

The keys of the new array are then returned as an array of values using the array_keys() PHP function.

Here is an example of the function in action.

$array = array(1,1,1,1,1,2,3,4,5,6,6,6,6,6,6,6,6,6,6);
echo '<pre>'.print_r($array,true).'
'; $array = remove_duplicated_values($array); echo ''.print_r($array,true).'';

Be aware that any keys that the original array has will be lost by the action of this function.

philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter


What about the built-in function array_unique? Used it in the past and seems to work fine for me as well. Usefull blog btw, thanks.
philipnorton42's picture
Submitted by philipnorton42 on Thu, 08/14/2008 - 10:28

Very true, you could use the array_unique() function. That function also preserves any keys that the original array has. The first key encountered will be used.

I always use array_unique function when I want remove duplicate entries in array. You give me new way to do that.

Thanks alot!

This is really interesting, You are a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more of your wonderful post. Also, I’ve shared your website in my social networks!

Thanks for the article. Array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys.

Add new comment