如果针是一个数组,我如何使用 in_array?

2022-01-25 00:00:00 arrays compare search php

我有 2 个数组,值将从数据库中加载,下面是一个示例:

I have 2 arrays, the value will be loaded from database, below is an example:

$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);

我要做的是检查$arr1中的所有值是否存在于$arr2中.上面的例子应该是 TRUE while:

What I want to do is to check if all the values in $arr1 exist in $arr2. The above example should be a TRUE while:

$arr3 = array(1,2,4,5,6,7);

比较 $arr1$arr3 将返回 FALSE.

comparing $arr1 with $arr3 will return a FALSE.

通常我使用 in_array 因为我只需要将单个值检查到数组中.但在这种情况下,不能使用 in_array.我想看看是否有一种简单的方法可以用最少的循环进行检查.

Normally I use in_array because I only need to check single value into an array. But in this case, in_array cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.

更新说明.

第一个数组将是一个包含唯一值的集合.第二个数组可以包含重复的值.在处理之前,它们都保证是一个数组.

First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.

推荐答案

使用 array_diff():

$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
  // all of $arr1 is in $arr2
}

相关文章