检查数组是否包含另一个数组的值


Check if array contains values of another array in the same order

我有两个数组,第一个是:

[4, 6, 2, 7, 5, 1]

第二种是

[2, 7, 5]

如何确定第一个数组是否包含第二个数组的SAME值(SAME顺序)。在这种情况下,函数将返回TRUE,因为序列2, 7, 5实际上存在于第一个数组中。它将为2, 5, 7返回FALSE。值存在于第一个数组中,但不是按那个确切的顺序。

是否有一个现有的PHP函数用于此?如果没有,我应该如何实现?

对于数组内容的常见情况:

$ar1 = [2, 4, 6, 2, 4, 7, 5, 1,];
$ar2 = [2, 7, 5];
// Find point where sub-array can start
$keys = array_keys($ar1, $ar2[0]); 
foreach($keys as $k) 
   // Check that sub-array is the same as the second array 
   if(array_slice($ar1, $k, count($ar2)) == $ar2) 
       { echo "Wow!"; break; }

如果数组只是数字,我建议使用一个技巧:

$a1 = [4, 6, 2, 7, 5, 1];
$a2 = [2, 7, 5];
// convert both arrays to strings, 
// add `,` in the beginning and end, see @splash58 comment
$a1_str = ',' . implode(',', $a1) . ',';
$a2_str = ',' . implode(',', $a2) . ',';
// check with strpos:
echo strpos($a1_str, $a2_str) !== false? 'Eq' : 'Not eq';