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!
It would be interesting to see a benchmark on the different approaches. π
LikeLiked by 1 person
Hey Niels π Agree! I think this is a good example https://3v4l.org/0D3MS, which is from https://stackoverflow.com/a/13483548
Output for 8.0.10
Size: 9943
0.000417 Total time – isset
0.092448 Total time – in_array
LikeLiked by 1 person
Woah, that’s a very clear result, Dat! π
LikeLiked by 1 person