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\
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;
}
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;
}
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)
.