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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?