1

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?

Anette D.
  • 25
  • 4

2 Answers2

2
$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
}
deceze
  • 510,633
  • 85
  • 743
  • 889
0
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;
    }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87