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.
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]);
}
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.
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. 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:
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;
}