in_array() is a standard function in php which can be used to check if a value exists in array, duh! but sometimes, when the array size is relativly large this function can take a long time
While it is quite easy to understand and use it as its intended but the problem comes when the size of the array is huge and use it for something as menial as finding if something exists in array. For a relatively smaller array will not affect the performance and thus you will never face the problem untill the system grows very big and you cannot figure why suddenly the response from server is very slow.
It is very important to understand the pitfalls and then make an educated decision as to weather you should use
in_array() or not. For example, if the array contains status of a github pull request then you can confidently say that the number of status in array will almost never be so big that it becomes a problem. In that case, it is okay to use
in_array(), just be sure not to be stupid enough to check for inverse unless necessary.
One way to look at the problem is to see if you can do anything to the array itself so that you don’t have to go through each element one by one (
in_array()) and instead just directly try to check if an element is there. For a simple array, it is possible.
If you are worries that a single dimensional array doesn’t have keys to begin with so how will it work ?
- Internally php array always have keys and values even a one dimensional array has keys from
0-ngenerally called as index.
- Flip will use those numbers or indices as values.
- The flip happens in place (original array gets updated) so you do not use extra space.
- Be aware that the resulting array will remove duplicate values because using them as keys mean they must be unique.
isset()will evaluate the value of the key so it will return false if that value is null.
array_key_exists()will only check if the key exists in the array.
- While this is a useful method be sure that you can actually face the problem before trying to over-engineer simple situations. For example, this logic is better used against a list of usernames than a list of user_roles.
- When the array is fairly complex, it serves better to first make the array simple and then checking what the result of
- Just found out
array_flip()is also probably
LastMod Saturday, April 9, 2022 (66900f7)