doushichun9409 2015-07-02 09:21
浏览 161
已采纳

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

I have a form that submits an array of user roles for processing by the server. Here is an example of the $data['roles'] posted by the form:

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

I want to check if $data['roles'] contains either one of the values 16, 17, 18 or 19. As you can see in the example it contains 16. in_array seems like the logical choice here, but passing an array of values as the needle of in_array doesn't work:

$special_values = array(16, 17, 18, 19);

if (in_array($special_values, $data['roles'])) {
    // this returns false
}

Neither does passing the exact same values in an array:

$special_values = array(5, 16);

if (in_array($special_values, $data['roles'])) {
    // this also returns false
}

Also, switching places between the two arrays as needle and haystack doesn't change the result. If I just ask if 16 is in the array, it works fine:

$special_value = 16;

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

The documentation gives examples of using arrays as needles, however it seems the structure needs to be exactly the same in the haystack for it to return true. But then I don't get why my second example doesn't work. I'm obviously doing something wrong or missing something here.

What is the best way to check if any of the values in one array exists in another array?

Edit: This question (possible duplicate) is not asking the same thing. I want to match any value in one array against any value in another. The linked question wants to match all values in one array against the values of another.

  • 写回答

2条回答 默认 最新

  • dtt5830659 2015-07-02 09:43
    关注

    This may help you

    Using array_intersect()

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

    Using in_array()

    $result = false;
    
    foreach ($special_values as $val) {
        if (in_array($val, $data['roles'], true)) {
            $result = true;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB yalmip 可转移负荷的简单建模出错,如何解决?
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?