Remove Duplicates from an Array
Sometimes you have an array of elements that may contain duplicate entries, but you do want any duplication. Randomly selected elements are a good example of this. If you add elements to an array one at a time using the random function, it can return the same value more than once.
Removing any duplicates is easy … just use array_unique().
$newarray=array_unique($oldarray);
Any time to identical entries are identified, the second one will be removed from the array. Remember that this may leave you with an array having missing index values. That is no worry if you are going through the array using the foreach() function, but if you want to use for($x=0;$x<12;++$x) you will have problems.
You can fix that by reordering your array keys using array_values():
$correctarray=array_values($newarray);
This will take the $newarray created in the earlier line, and replace the key values with new ones, starting at zero and proceeding sequentially.
Filed under: Functions | Leave a Comment
Search
-
You are currently browsing the PHP Basics weblog archives.
No Responses Yet to “Remove Duplicates from an Array”