Lizard
Lizard

Reputation: 45022

Number of actions of array_unique PHP

Does anyone know the Big O of array_unique()?

I haven't gone through the source, but I would imagine it loops through each value and checks to to see if it is in the array which would be O(n^2) is this correct?

Thanks

Upvotes: 3

Views: 1253

Answers (1)

starrify
starrify

Reputation: 14761

It's O(nlogn) since it uses sorting instead of your O(n^2) scanning.

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

Quoted from http://php.net/manual/en/function.array-unique.php

EDIT: Remember to Google it, check the manual, check for existing questions, and then ask it.

Upvotes: 3

Related Questions