Searching for consecutive values in an array

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

    This does what you're asking for, it's somewhat specific as all arrays must be non-keyed, and have unique values.

    Additionally, in this version the arrays can only contain integer or string values. If you need any NULL, object, float and arrays as well, a part of it needs to be changed from the array_flip() + isset() to array_search().

    CodePad / Gist

    The relevant part is to compare a slice of the array you search in (here $in) with the array you search for (here $for):

    array_slice($in, $pos, $len) === $for
    

    $pos has been looked up earlier for the first value of $for, $len is count($for).

提交回复
热议问题