<?php
function array_group(array $arr1, callable $compare): array {
$groups = [];
$group = [];
$prev = NULL;
foreach ($arr1 as $value) {
if ($group && !$compare($prev, $value)) {
$groups[] = $group;
$group = [];
}
$group[] = $value;
$prev = $value;
}
if ($group) {
$groups[] = $group;
}
return $groups;
}
$arr1 = array(1,2,2,3,1,2,0,4,5,2);
$compare = fn ($a, $b) => $a <= $b;
print_r(array_group($arr1, $compare));
- Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 0
[1] => 4
[2] => 5
)
[3] => Array
(
[0] => 2
)
)
preferences:
72.87 ms | 407 KiB | 5 Q