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

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

高洛峰
高洛峰Original
2016-12-22 13:37:381462browse

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(&#39;first&#39; => null, &#39;second&#39; => 4);
// returns false
isset($search_array[&#39;first&#39;]);
// returns true
array_key_exists(&#39;first&#39;, $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(&#39;,&#39;, $array);
    $str = &#39;,&#39; . $str . &#39;,&#39;;
    $item = &#39;,&#39; . $item . &#39;,&#39;;
    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!


Statement:
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