Home > Back-end >  The fatest way to check if a value is in array in php
The fatest way to check if a value is in array in php

Time:07-31

I want to check if a value is in an array:

$a=array("abc","def","ghi");
if(in_array("def",$a)) echo "yes";
else echo "no";

However, the search is slow when the array is large, which makes me think maybe php does not sort the array before searching.

What is the fastest way to search an unsorted array?

CodePudding user response:

The fastest way is to use hashes as keys for the value and then check if the key is present with isset(). This will be faster, because the hashmap is internally searched as a binary tree.

Instead of converting the array with a function, you better create directly that way.

$a = ["abc", "def", "ghi"];
$b = makeFastArray($a);
echo isset($b[sha1('def')]) ? "true" : "false";
echo PHP_EOL;
echo isset($b[sha1('xyz')]) ? "true" : "false";

function makeFastArray($array): array {
    $data = [];
    foreach($array as $value) {
        $data[sha1($value)] = $value;
    }

    return $data;
}

Output:

true
false
  • Related