3v4l.org

run code in 300+ PHP versions simultaneously
<?php $input = [1, 2, 3, 5, 4, 7, 6, 8, 9]; $batches = generateBatches($input); function generateBatches($input) { $length = count($input); if (0 === $length) { return []; } $batches = []; $prev = $input[0]; $currentBatch = [$prev]; for ($i = 1; $i < $length; $i++) { if ($i < $prev) { $batches[] = $currentBatch; $currentBatch = []; } $currentBatch[] = $prev = $input[$i]; } $batches[] = $currentBatch; return $batches; } print_r($batches);

preferences:
34.23 ms | 404 KiB | 5 Q