fork(4) download
  1. <?php
  2.  
  3. $needle = array(1,1);
  4. $haystack1 = array(0,1,0,0,0,1,1,0,1,0);
  5. $haystack2 = array(0,0,0,0,1,0,1,0,0,1);
  6.  
  7. echo "needle ".(subarray_exists($needle, $haystack1) ? "exists" : "does not exist")." in haystack1\n";
  8. echo "needle ".(subarray_exists($needle, $haystack2) ? "exists" : "does not exist")." in haystack2\n";
  9.  
  10.  
  11. function subarray_exists(array $needle, array $haystack) {
  12. if (count($needle) > count($haystack)) {
  13. return false;
  14. }
  15.  
  16. $needle = array_values($needle);
  17. $iterations = count($haystack) - count($needle) + 1;
  18. for ($i = 0; $i < $iterations; ++$i) {
  19. if (array_slice($haystack, $i, count($needle)) == $needle) {
  20. return true;
  21. }
  22. }
  23.  
  24. return false;
  25. }
Success #stdin #stdout 0.02s 13064KB
stdin
Standard input is empty
stdout
needle exists in haystack1
needle does not exist in haystack2