Home > Back-end >  Find qualifying subsets and return value that immediately follows
Find qualifying subsets and return value that immediately follows

Time:08-04

Could someone help me with a function to compare if there is an array inside another and return the next item every time it finds this array inside?

For example

$array1 = [0,0,0,1,1,0,1,1,0,0,1,1,0,0,1];
$array2 = [1,1,0];

In this case, the exact sequence of elements in $array2 is found 3 times.

The values that follow the sequence are:

  • 1st combination = 1
  • 2nd combination = 0
  • 3rd combination = 0

Visualization:
|---| marks the sequence matches, ^ marks the value that should be returned.

0,0,0,1,1,0,1,1,0,0,1,1,0,0,1
      |---| ^
            |---| ^
                    |---| ^

CodePudding user response:

I reckon it is simpler to read your data as a string instead of iterating elements in their current array form.

Just use a lookbehind pattern and match the next occurring integer.

Code: (Demo)

$haystack = [0,0,0,1,1,0,1,1,0,0,1,1,0,0,1];
$needle = [1,1,0];

$regex = sprintf(
    '/(?<=%s,)\d /',
    implode(',', $needle)
);

var_export(
    preg_match_all($regex, implode(',', $haystack), $m)
    ? $m[0]
    : []
);

Output:

array (
  0 => '1',
  1 => '0',
  2 => '0',
)

Or an approach that processes the data in array form, can make iterated calls of array_slice() to achieve the same result. (Demo)

$needleCount = count($needle);
$result = [];
foreach ($haystack as $i => $straw) {
    $start = $i - $needleCount;
    if (
        $start >= 0
        && $needle === array_slice($haystack, $start, $needleCount)
    ) {
        $result[] = $straw;
    }
}
  • Related