简体   繁体   中英

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);

A working array_slice() would still need a loop as far as I can work out:

foreach(array_keys($haystack, reset($needle)) as $offset) {
    if($needle == array_slice($haystack, $offset, count($needle))) {
        // yes, contains needle
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM