Searching for consecutive values in an array

前端 未结 3 842
面向向阳花
面向向阳花 2021-01-23 17:04

What\'s the best way to search for consecutive values in an array?

For example, searching for array(\'a\', \'b\') in array(\'x\', \'a\', \'b\', \'c\

3条回答
  •  轮回少年
    2021-01-23 17:17

    Haven't tested this, but something like this should do:

    function consecutive_values(array $needle, array $haystack) {
        $i_max = count($haystack)-count($needle);
        $j_max = count($needle);
        for($i=0; $i<$i_max; ++$i) {
            $match = true;
            for($j=0; $j<$j_max; ++$j) {
                if($needle[$j]!=$haystack[$i+$j]) {
                    $match = false;
                    break;
                }
            }
            if($match) {
                return $i;
            }
        }
        return -1;
    }
    

提交回复
热议问题