Over the past few months I’ve been working a lot with PHP and some of my work has been heavily reliant on searching for values in long arrays. PHP has a nice function for doing just this (
in_array) and naturally I assumed this would be the best way of doing it. However, after finding the program quite sluggish, I set out to improve matters and the following is just a very simple trick which I found made quite a difference.
in_array function searches the array for the ‘needle’ value which is inevitably going to take time, e.g. a linear search would have time complexity O(n). In contrast, PHP’s
isset function has time complexity O(1); no matter how efficient the searching algorithm, it can never begin to match that. The idea of this trick is therefore to replace every occurrence of
in_array with one of
isset. This is made remarkably easy as PHP also provides a function which will create an inverted array (
array_flip); where each key in the array is swapped with its respective value. See code below for the two approaches…
$lookup = array( 'values', 'here' ); // lookup array /* CHECK FOR VALUE USING in_array */ if ( in_array( 'required value', $lookup ) ) echo 'Found'; /* CHECK FOR VALUE USING isset */ $lookup = array_flip( $lookup ); // flip keys and values if ( isset( $lookup['required value'] ) ) echo 'Found';
How this can be implemented within your system depends greatly on what you are trying to achieve and in some situations it isn’t viable, e.g. when you have a 2D array or an array of objects1. Alternatively, the system can be designed appropriately from the outset without ever needing to use
Intrigued to know what difference it made, I knocked together this script to measure the execution time of the two approaches. It uses a 1000 element array of chars and even with the array flip included in the time, the isset approach took just 0.0083% of the time of the in_array approach; that’s 120 times faster. Well worth keeping in mind and it vastly improved the performance of my program.
1 PHP Manual, “Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type”