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 through custom functions to achieve):
1. Flip the array key and value, and use isset to determine whether the key exists in the array
The code is as follows:
/**
* 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 you don’t use array_key_exists 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.
The code is as follows:
$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 determine
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. An example is as follows:
The code is 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;
}