Remove Duplicate Entries In A PHP Array

6th August 2008

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

  1. function remove_duplicated_values($array){
  2. $newArray = array();
  3. foreach($array as $key=>$val){
  4. $newArray[$val] = 1;
  5. }
  6. return array_keys($newArray);
  7. }

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.

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

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

Comments

Permalink
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.

philipnorton42 (Thu, 08/14/2008 - 09:28)

Permalink

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

Thanks alot!

dinh vi gps (Thu, 12/08/2011 - 08:23)

Permalink
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!

Ban nha duoi 2… (Fri, 03/03/2017 - 16:04)

Permalink
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.

Made In Japan (Wed, 07/12/2017 - 10:16)

Permalink
Any news on this front? We, too, are left wistful @ the dupe accumulation issue in the Library (not playlist)

Diet Kien Cua Nhat (Fri, 11/24/2017 - 10:40)

Permalink
The simplest and most readable way to create an array of unique values as a developer is array_unique, but this comes with some scalability problems as it's worst-case runtime becomes a hindrance as the array size grows.

Quan Lot Gu Uniqlo (Wed, 01/10/2018 - 09:01)

Permalink

I want remove duplicate entries in array. You give me new way to do that.

Thanks alot!

Visa Tan Tam (Mon, 06/25/2018 - 18:09)

Permalink

Very nice, you should use the array_unique() function. That function also preserves any keys that the original array has. 

Visa Tan Tam (Fri, 07/20/2018 - 03:05)

Permalink

Nice, you could also use the array_unique() function. It preserves any keys that the original array has. 

Visa Tan Tam (Fri, 07/20/2018 - 03:07)

Add new comment

The content of this field is kept private and will not be shown publicly.