Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
    
stackoverflow.com/questions/12867315/… does that answer your question? – Harri Oct 29 '13 at 20:09
1  
This seems like homework. Please post what you have tried so far. – puelo Oct 29 '13 at 20:09
    
Tip: Have a look under Related over to the right >>> – Fred -ii- Oct 29 '13 at 20:09
up vote 1 down vote accepted
$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
}
share|improve this answer
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;
    }
}
share|improve this answer
    
And please, this should be faster than array_slice? – Anette D. Oct 29 '13 at 21:01
    
@Anette D.: I haven't timed it, but it doesn't fail like the array slice() example. – AbraCadaver Oct 29 '13 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); – AbraCadaver Oct 29 '13 at 21:10
    
Added working array_slice(). Shouldn't use $needle[0] cuz it could be any number or associative. – AbraCadaver Oct 29 '13 at 21:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.