davidlee
davidlee

Reputation: 6167

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.

Upvotes: 4

Views: 5475

Answers (4)

Taufik Nurrohman
Taufik Nurrohman

Reputation: 3409

Implode the outer array with a delimiter that is forbidden to be written in the array value:

$x = "\x1a";
$array = $x . implode($x, $array) . $x;
foreach ($a as $b) {
    if (strpos($array, $x . $b . $x) !== false) {
        // in array
    }
}

Upvotes: 0

AntonioCS
AntonioCS

Reputation: 8496

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,

Upvotes: 3

greg0ire
greg0ire

Reputation: 23255

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

Upvotes: 1

Gordon
Gordon

Reputation: 316969

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.

Upvotes: 6

Related Questions