Home > Backend Development > PHP Tutorial > 2 customized PHP in_array functions to solve the efficiency problem of judging in_array from large amounts of data_PHP tutorial

2 customized PHP in_array functions to solve the efficiency problem of judging in_array from large amounts of data_PHP tutorial

WBOY
Release: 2016-07-13 10:34:34
Original
936 people have browsed it

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;

}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/751221.htmlTechArticleBut if the array is relatively large, the performance will decrease and the running time will be longer. If the array is For optimization in the case of large arrays, here are two methods (both through custom functions...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template