Two custom PHPin_array functions solve the efficiency of in_array judgment by a large amount of data

Source: Internet
Author: User
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.