Collection::sliding()
Create a sliding window of overlapping chunks from a collection — perfect for moving averages, comparisons, and sequential analysis.
Overview
sliding() returns a new collection of overlapping "windows" of a given size. Unlike chunk() which creates non-overlapping groups, sliding() moves one item at a time (or by a custom step), giving you every consecutive sub-sequence.
Usage
$collection = collect([1, 2, 3, 4, 5]);
$collection->sliding(2);
// [[1, 2], [2, 3], [3, 4], [4, 5]]
$collection->sliding(3);
// [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
With a custom step size:
$collection->sliding(size: 3, step: 2);
// [[1, 2, 3], [3, 4, 5]]
Real-World Example
Calculating a 7-day moving average:
$dailyRevenue = collect($revenueData); // 30 days of data
$movingAverages = $dailyRevenue
->sliding(7)
->map(fn ($window) => [
'date' => $window->last()['date'],
'average' => $window->avg('amount'),
]);
Detecting consecutive duplicate values:
$logs = collect($statusLogs);
$repeated = $logs->sliding(2)
->filter(fn ($pair) => $pair->first()['status'] === $pair->last()['status'])
->map(fn ($pair) => $pair->first());
When to Use
- Moving averages, rolling sums, or time-series analysis
- Finding consecutive patterns in sequences
- Comparing each item with its neighbors
- Signal processing or data smoothing