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?

3
  • stackoverflow.com/questions/12867315/… does that answer your question? Commented Oct 29, 2013 at 20:09
  • 1
    This seems like homework. Please post what you have tried so far. Commented Oct 29, 2013 at 20:09
  • Tip: Have a look under Related over to the right >>> Commented Oct 29, 2013 at 20:09

2 Answers 2

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
}
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;
    }
}
4
  • And please, this should be faster than array_slice? Commented Oct 29, 2013 at 21:01
  • @Anette D.: I haven't timed it, but it doesn't fail like the array slice() example. Commented Oct 29, 2013 at 21:04
  • Array_slice works for your specific example, but not: $haystack = array(1,2,3,3,4,5,6,7,8,9,10); Commented Oct 29, 2013 at 21:10
  • Added working array_slice(). Shouldn't use $needle[0] cuz it could be any number or associative. Commented Oct 29, 2013 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.