php - in_array多个值
如何检查多个值,例如:
$arg = array('foo','bar');
if(in_array('foo','bar',$arg))
这是一个例子,所以你了解得更好,我知道它不会起作用。
daryl asked 2019-04-14T11:09:21Z
7个解决方案
162 votes
将目标与干草堆相交,并确保交叉点与目标精确相等:
$haystack = array(...);
$target = array('foo', 'bar');
if(count(array_intersect($haystack, $target)) == count($target)){
// all of $target is in $haystack
}
请注意,您只需要验证结果交集的大小与目标值数组的大小相同,即$target是$haystack的超集。
要验证$target中的至少一个值是否也在$haystack中,您可以执行以下检查:
if(count(array_intersect($haystack, $target)) > 0){
// at least one of $target is in $haystack
}
Mark Elliot answered 2019-04-14T11:09:48Z
133 votes
作为开发人员,您应该开始学习集合操作(差异,联合,交集)。 您可以将数组想象为一个“集合”,以及您正在搜索另一个的键。
检查是否存在所有针头
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present
检查是否存在任何针头
function in_array_any($needles, $haystack) {
return !empty(array_intersect($needles, $haystack));
}
echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present
Rok Kralj answered 2019-04-14T11:10:27Z
10 votes
if(in_array('foo',$arg) && in_array('bar',$arg)){
//both of them are in $arg
}
if(in_array('foo',$arg) || in_array('bar',$arg)){
//at least one of them are in $arg
}
RiaD answered 2019-04-14T11:10:46Z
5 votes
离开@Rok Kralj回答(最好的IMO)来检查大海捞针是否存在任何针头,你可以使用(bool)而不是!!,这有时会在代码审查期间造成混淆。
function in_array_any($needles, $haystack) {
return (bool)array_intersect($needles, $haystack);
}
echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present
[https://glot.io/snippets/f7dhw4kmju]
sMyles answered 2019-04-14T11:11:19Z
3 votes
恕我直言Mark Elliot的解决方案是解决这个问题的最佳解决方案。 如果你需要在数组元素和PHP 5.3之间进行更复杂的比较操作,你可能还会考虑以下内容:
// First Array To Compare
$a1 = array('foo','bar','c');
// Target Array
$b1 = array('foo','bar');
// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
if (!in_array($x,$b1)) {
$b=false;
}
};
// Actual Test on array (can be repeated with others, but guard
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);
这取决于关闭; 比较功能可以变得更加强大。祝好运!
maraspin answered 2019-04-14T11:11:53Z
0 votes
if(empty(array_intersect([21,22,23,24], $check_with_this)) {
print "Not found even a single element";
} else {
print "Found an element";
}
array_intersect()返回一个数组,其中包含所有参数中存在的array1的所有值。 请注意,密钥保留。
返回一个数组,其中包含array1中所有值的所有值,其值存在于所有参数中。
empty() - 确定变量是否为空
如果var存在且具有非空的非零值,则返回FALSE。 否则返回TRUE。
Umesh Patil answered 2019-04-14T11:12:42Z
0 votes
根据PSR-12(取代PSR-2;目前的草案状态):
if (
$expr1
&& $expr2
) {
// if body
}
要么
if (
$expr1 &&
$expr2
) {
// if body
}
[https://www.php-fig.org/psr/]
PSR-12
DRB answered 2019-04-14T11:13:26Z