views:

97

answers:

3

Dear all,

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.

+1  A: 

I think you are searching for the intersection of $a an $array, aren't you? If yes, simply use array_intersect()

greg0ire
I think you mean `array_intersect()`
Dennis Haarbrink
@Dennis Haarbrink: Yes, my bad.
greg0ire
+5  A: 

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.

Gordon
+1  A: 

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,

AntonioCS