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().


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():


This will take the $newarray created in the earlier line, and replace the key values with new ones, starting at zero and proceeding sequentially.


No Responses Yet to “Remove Duplicates from an Array”

  1. Leave a Comment

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: