Search for sequential values โ€‹โ€‹in an array

What is the best way to find sequential values โ€‹โ€‹in an array?

For example, looking for array('a', 'b') in array('x', 'a', 'b', 'c') will give 1 , because the values โ€‹โ€‹first appear sequentially at this index.

+1
source share
3 answers

Did not test this, but something like this:

 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; } 
0
source

This is probably not optimal, but rather 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; } 
0
source

This does what you ask for, it is somewhat specific, since all arrays must be unblocked and have unique values.

In addition, in this version, arrays can contain only integer or string values. If you need any NULL, object, float and arrays, part of it should be changed from array_flip() + isset() to array_search() .

CodePad / Gist

The relevant part is to compare the fragment of the array you are looking for (here $in ), with the array you are looking for (here $for ):

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

$pos was scanned earlier for the first value of $for , $len is count($for) .

0
source

Source: https://habr.com/ru/post/1440256/


All Articles