We may have used in_array to determine whether a data is in an array. Generally, our array may have relatively small data, which has no impact on performance, so I don't care too much about it, but if the array is relatively large, the performance will decrease and the running will take a little longer, then what if we optimize the array, the two methods are described below (both implemented through user-defined functions ):
1. the array key and value are flipped, and isset is used to determine whether the key exists in the array.
/** * in_array is too slow when array is large */public static function inArray($item, $array) { $flipArray = array_flip($array); return isset($flipArray[$item]);}
We may also ask why we do not use array_key_exists to judge whether isset is used? Next let's take a look at the comparison between array_key_exists () and isset:
Isset () does not return TRUE for NULL values in the array, while array_key_exists () does.
null, 'second' => 4);// returns falseisset($search_array['first']);// returns truearray_key_exists('first', $search_array);?>
2. connect with implode and use strpos to determine
Use the implode function + comma to connect and use strpos for determination. In php, the string location is very fast, especially when the data volume is large. However, it should be noted that "," must be added at the beginning and end, which is more rigorous. For example, user1, user2, and user3. check user1 when searching ,. Also use strpos! = False, because the first one returns 0. Example:
/** * in_array is too slow when array is large */public static function inArray($item, $array) { $str = implode(',', $array); $str = ',' . $str . ','; $item = ',' . $item . ','; return false !== strpos($item, $str) ? true : false;}
More than two custom PHP in_array functions to solve the efficiency problem of in_array judgment by a large amount of data!