比in_array快? [英] faster than in_array?

查看:202
本文介绍了比in_array快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个值进行比较,以一组阵列。不过,我需要在比较的foreach多个值。如果使用in_array,它可以是缓慢的,真正的慢。有没有更快的替代方案?我现在的code是

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);
}

感谢你。

推荐答案

您可以使用的 和array_diff 来计算对 $ A 阵列之间的差异> $阵列。这会给你所有的值不在 $阵列 $ 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.

从手动例如:

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

Array
(
    [1] => blue
)

或者你也可以使用 和array_intersect 发现那些在那些阵列。

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

和array_intersect 从PHP手册举例:

$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.

这篇关于比in_array快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆