The keys of the array are hashed, so looking at them simply requires calling the hash function and indexing into the hash table. So array_flip() is O (N), and the search for the array key is O (1), so Y searches O (Y) + O (N).
Array values ββare not hashed, so a linear search is required to find them. This is O (N), so Y is looking for O (N * Y).
Assuming that the search for values ββis evenly distributed across the array, the average case of a linear search should compare N / 2 elements. Thus, array_flip() should take the time to call 2 array_search() , since it should check for N elements.
There are additional overheads in creating a hash table. However, PHP uses copy-on-write, so it does not need to copy keys or values ββduring array_flip() , so this is not so bad. For a small number of searches, the first method may be faster. You will need to compare it to find a breakeven point.
Barmar
source share