Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

faster than in_array?

I need to compare a value to a set of array. However, I need to compare multiple values in foreach. If using in_array, it can be slow, real slow. Is there any faster alternative? My current code is

foreach($a as $b){
   in_array($b, $array);
}

Thank you.

like image 508
davidlee Avatar asked Dec 28 '22 08:12

davidlee


2 Answers

You could use array_diff to compute the difference between the $a array against $array. This would give you all the values not in $array or $a.

Example from Manual:

$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
print_r( array_diff($array1, $array2) );

Array
(
    [1] => blue
)

Or you can use array_intersect to find those that are in those arrays.

array_intersect Example from PHP Manual:

$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
print_r( array_intersect($array1, $array2) );

Array
(
    [a] => green
    [0] => red
)

Pick the one you need.

like image 61
Gordon Avatar answered Jan 08 '23 03:01

Gordon


If you can treat the array as a hash:

$array = array('value' => 1);

Then in the foreach do this:

foreach($a as $b){
    isset($array[$b]);
}

I just copied&pasted your example, I suppose there is more code but basically using the isset is a lot faster than using the in_array function,

like image 40
AntonioCS Avatar answered Jan 08 '23 04:01

AntonioCS