Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Remove duplicate values from an array?
Index -> Programming, PHP -> PHP Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
HelloWorld




PostPosted: Mon Mar 23, 2009 1:54 am   Post subject: Remove duplicate values from an array?

I just started learning PHP, and I've been having lots of fun. I made a little tool for myself that works great, but I want to improve it. My tool does a search, and returns results in an array. Sometimes there can be duplicates in the results, how can I remove those from the array?

Here is what I mean:

Array
)
[0] => blue
[1] => red
[2] => orange
[3] => green
[4] => orange
[5] => red
[6] => yellow
)

I want to remove the repeats. So in the end it will be:

Array
)
[0] => blue
[1] => red
[2] => orange
[3] => green
[4] => yellow
)

Thanks Smile.
Sponsor
Sponsor
Sponsor
sponsor
btiffin




PostPosted: Mon Mar 23, 2009 11:22 am   Post subject: RE:Remove duplicate values from an array?

Look at array_unique

Cheers
A.J




PostPosted: Mon Mar 23, 2009 11:30 am   Post subject: RE:Remove duplicate values from an array?

array_unique or try hashing the values. maybe store the colors as numbers.
HelloWorld




PostPosted: Mon Mar 23, 2009 2:40 pm   Post subject: RE:Remove duplicate values from an array?

Great. Thanks for the help. Smile
DanielG




PostPosted: Sat Mar 28, 2009 7:52 pm   Post subject: RE:Remove duplicate values from an array?

if your arrays are tiny, you can always just compare EVERY value with EVERY value before it to see if there is a repeat.
Analysis Mode




PostPosted: Sat Mar 28, 2009 8:26 pm   Post subject: Re: Remove duplicate values from an array?

Why don't you sort them? That way, you can delete duplicates in O(N) time and not O(N^2) time.
DemonWasp




PostPosted: Sat Mar 28, 2009 8:36 pm   Post subject: RE:Remove duplicate values from an array?

...or you could insert all the values into some sort of Set object (preferably the PHP equivalent of a HashSet), which would do it all in O ( N ) time - whereas sorting first requires O ( N * log ( N ) ) time.
Display posts from previous:   
   Index -> Programming, PHP -> PHP Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 7 Posts ]
Jump to:   


Style:  
Search: