PHP: Check if array contains another array values (in specific order)

I have an array:

$haystack = array(1,2,3,4,5,6,7,8,9,10...);
$needle = array(3,4,5);
$bad_needle = array(3,5,4);

And I need to got true if I check if haystack contains a needle. But I also need false if I check if haystack contains bad_needle. Tip without foreach for all haystacks and needles?


$offset = array_search($needle[0], $haystack);
$slice  = array_slice($haystack, $offset, count($needle));
if ($slice === $needle) {
    // yes, contains needle
}

This fails if the values in $haystack are not unique though. In this case, I'd go with a nice loop:

$found  = false;
$j      = 0;
$length = count($needle);

foreach ($haystack as $i) {
    if ($i == $needle[$j]) {
        $j++;
    } else {
        $j = 0;
    }
    if ($j >= $length) {
        $found = true;
        break;
    }
}

if ($found) {
    // yes, contains needle
}

var_dump(strpos(implode(',', $haystack), implode(',', $needle)) !== false);

var_dump(strpos(implode(',', $haystack), implode(',', $bad_needle)) !== false);

尽我所能,一个正在工作的array_slice()仍然需要一个循环:

foreach(array_keys($haystack, reset($needle)) as $offset) {
    if($needle == array_slice($haystack, $offset, count($needle))) {
        // yes, contains needle
        break;
    }
}
链接地址: http://www.djcxy.com/p/75354.html

上一篇: 如何大写字符串中每个单词的第一个字符

下一篇: PHP:检查数组是否包含其他数组值(按特定顺序)