Remove Duplicate Entries In A PHP Array

×

Error message

Warning: apc_store(): Potential cache slam averted for key 'www.hashbangcode.com::cache_bootstrap::variables' in DrupalAPCCache->set() (line 206 of /var/www/www.hashbangcode.com/2014-03-22-2105/docroot/sites/all/modules/contrib/apc/drupal_apc_cache.inc).

Wednesday, August 6, 2008 - 09:21

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

1
2
3
4
5
6
7
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.

1
2
$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.

Category: 
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

Comments

What about the built-in function array_unique? Used it in the past and seems to work fine for me as well. http://uk2.php.net/manual/en/function.array-unique.php 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!

Add new comment