Link to home
Start Free TrialLog in
Avatar of rgb192
rgb192Flag for United States of America

asked on

remove duplicates from array

given an array
bob real estate
susan real estate
susan real estate
susan real estate
susan real estate
susan real estate
susan real estate
mary apartments
edward locators

Open in new window



I want to remove duplicates
bob real estate
susan real estate
mary apartments
edward locators

Open in new window

Avatar of Mysidia
Mysidia
Flag of United States of America image

This looks like a homework problem;  it's so trivial,   that I don't think a PHP developer with a real-world application would legitimately have any issues with duplicate item removal.     So I will simply refer you to this article:
  http://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php

The page at the stackoverflow link contains examples,  and explains how to remove elements from an array.

Basically,  by calling   unset()  on the array element.
Then,  after the duplicate elements are removed, you can reindex the array by calling the array_splice() function.

My suggestion for the duplicate removal logic is that you use   a nested for loop,     to  look at each item in the array,  and then  for each item:   loop through the array,  searching for other items that are the same.

Then if you find a pair of  different array elements that are the same,    pick one of the two to  delete.


A better alternative  may be  to  scan for duplicates before populating the array;  so, instead of removing duplicates,  you avoid inserting duplicates in the first place  ---  this is what would generally be used.
ASKER CERTIFIED SOLUTION
Avatar of Hagay Mandel
Hagay Mandel
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

array unique is easiest

thanks