Computer Science Canada

Remove duplicate values from an array?

Author:  HelloWorld [ 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.

Author:  btiffin [ Mon Mar 23, 2009 11:22 am ]
Post subject:  RE:Remove duplicate values from an array?

Look at array_unique

Cheers

Author:  A.J [ 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.

Author:  HelloWorld [ Mon Mar 23, 2009 2:40 pm ]
Post subject:  RE:Remove duplicate values from an array?

Great. Thanks for the help. Smile

Author:  DanielG [ 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.

Author:  Analysis Mode [ 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.

Author:  DemonWasp [ 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.


: