PHP: in_array is very slow for a huge array

Definitely not something new but this experience gave me good reason to understand how a function works under the hood.

in_array() goes through all items in a provided array and see if any existing item exists in the array. It’s not an issue if the array has only a few items. However, when it has thousands or even million items, this function is no longer usable!

Instead, a good idea is to flip values to become keys and vice versa. It’s pretty simple if all values are unique then we can just use array_flip() for this purpose and search with new keys (or old values). Good trick indeed! The reason under the hood is that array keys are implemented with Hashtable.

Otherwise, it may be a bit more complicated and we may need to do some other tricks but it can still work!

This conversation suggests using isset(). However, basically it’s still my idea above with a different way telling about that. Even though, it is still a good read!

3 thoughts on “PHP: in_array is very slow for a huge array

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s