PHP: Detecting a particular sequence of elements in an array

arrays, php, sequence

Solution

Join the arrays, and check for the strpos of the needle.

if ( strpos( join($haystack1), join($needle) ) >= 0 ) {
    echo "Items found";
}

Demo: http://codepad.org/F13DLWOI

Warning

This will not work for complicated items like objects or arrays within the haystack array. This method is best used with itesm like numbers and strings.

Problem

How do I detect if a certan sequence of elements is present in an array? E.g. if I have the arrays and needle ``` $needle = array(1,1); $haystack1 = array(0,1,0,0,0,1,1,0,1,0); $haystack2 = array(0,0,0,0,1,0,1,0,0,1); ``` How does one detect if the subset $needle is present in e.g. $haystack1? This method should return TRUE for $haystack1 and FALSE for $haystack2. Thanks for any suggestions!

Original source