Remove Duplicate Entries In A PHP Array

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).'</pre>';
$array = remove_duplicated_values($array);
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

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.
Name
Philip Norton
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!

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!
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.
Permalink
Any news on this front? We, too, are left wistful @ the dupe accumulation issue in the Library (not playlist)
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.
Permalink

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

Thanks alot!

Permalink

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

Permalink

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

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.