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.
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With