Searching for consecutive values in an array

前端 未结 3 800
面向向阳花
面向向阳花 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:22

    This is probably sub-optimal but is fairly concise:

    $needle = array('a', 'b');
    $haystack = array('x', 'a', 'b', 'c');
    
    function searchInArray($haystack, $needle)
    {
        $keys = array_search($haystack, $needle[0]);
    
        foreach ($keys as $key) {
            $endPos = $key + count($needle);   
            for ($i=1; $i<$count($needle); $i++) {
                if ($needle[$i] == $haystack[$key + $i]) {
                    return $key;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题