But if the array is relatively large, the performance will decrease and the running time will be longer. So if you want to optimize for large arrays, here are two methods (both implemented through custom functions):
1. Flip the array key and value, and use isset 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]); }
You may also ask why array_key_exists is not used for judgment instead of using isset? Let’s look at the comparison between array_key_exists() and isset():
isset() will not return TRUE for NULL values in the array, but array_key_exists() will.
<?php $search_array = array('first' => null, 'second' => 4); // returns false isset($search_array['first']); // returns true array_key_exists('first', $search_array); ?>
2. Use implode to connect, and directly use strpos to judge.
Use implode function + comma to connect, and directly use strpos to judge. The string position in PHP is very fast, especially when the amount of data is large. However, it should be noted that "," must be added at the beginning and end, which is more rigorous. For example: ,user1,user2,user3, when searching, search for ,user1. Also use strpos! == false, because the first one will return 0. Examples are as follows:
/** * 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 2 customized PHP in_array functions to solve the efficiency problem of judging in_array from large amounts of data. For related articles, please pay attention to the PHP Chinese website!