如何检查数组中的任何值是否存在于另一个数组中


How can I check if any value in an array is present in another array?

我有一个表单,它提交一组用户角色供服务器处理。以下是表单发布的$data['roles']的示例:

Array ( [0] => 5 [1] => 16 )

我想检查$data['roles']是否包含值16、17、18或19中的任何一个。正如您在示例中看到的,它包含16个。in_array似乎是这里的逻辑选择,但传递值的数组作为in_array的指针是行不通的:

$special_values = array(16, 17, 18, 19);
if (in_array($special_values, $data['roles'])) {
    // this returns false
}

在数组中传递完全相同的值也不行:

$special_values = array(5, 16);
if (in_array($special_values, $data['roles'])) {
    // this also returns false
}

此外,在两个数组之间切换位置并不会改变结果。如果我只是问16是否在数组中,它运行良好:

$special_value = 16;
if (in_array($special_value, $data['roles'])) {
    // this returns true
}

该文档给出了使用数组作为指针的示例,但似乎需要在大海捞针中使用完全相同的结构才能返回true。但我不明白为什么我的第二个例子不起作用。我显然做错了什么或者错过了什么。

检查一个数组中是否存在任何值的最佳方法是什么?

编辑:这个问题(可能重复(不是在问同样的问题。我想将一个数组中的任何值与另一个数组的任何值进行匹配。关联问题希望将一个数组中的所有值与另一个数组的值相匹配。

这可能有助于

使用array_intersect()

$result = array_intersect($data['roles'], array(16, 17, 18, 19));
print_r($result);

使用in_array()

$result = false;
foreach ($special_values as $val) {
    if (in_array($val, $data['roles'], true)) {
        $result = true;
    }
}

bet的方法是使用array_diff和空函数,我认为:

if ( ! empty(array_diff($special_values, $data['roles']))) {
    throw new Exception('Some of special values are not in data roles');
}

如果要返回出现在两个数组中的值,则可以使用array_incross。