Skip to content

Instantly share code, notes, and snippets.

@wryk
Last active January 10, 2020 19:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wryk/4a48034ba7558d23ed88b2e46ab4f9b7 to your computer and use it in GitHub Desktop.
Save wryk/4a48034ba7558d23ed88b2e46ab4f9b7 to your computer and use it in GitHub Desktop.
group consecutive values in array with predicate
<?php
$groupBy = function (array $xs, callable $f) {
reset($xs);
$r = [];
$t = [];
while (array_key_exists(key($xs), $xs)) {
$x = current($xs);
$t[] = $x;
$nx = next($xs);
if (!array_key_exists(key($xs), $xs) || !$f($x, $nx)) {
$r[] = $t;
$t = [];
}
}
return $r;
};
$strictlyEqual = function ($a, $b) {
return $a === $b;
};
var_dump($groupBy([], $strictlyEqual));
var_dump($groupBy([false], $strictlyEqual));
var_dump($groupBy([false, false, true, false, true, true], $strictlyEqual));
var_dump($groupBy([1, 2, 1], $strictlyEqual));
var_dump($groupBy([1, 2, 2, 3, 3, 4, 5, 6, 6], $strictlyEqual));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment