php-standard-library/range
Range types for integer sequences with built-in iteration support. Create, traverse, and manipulate numeric ranges with a clean, standard-library style API. Part of the PHP Standard Library project; see docs, contribute, or report issues on GitHub.
Installation
composer require php-standard-library/range
No additional configuration is required—just autoload the package.
First Use Case: Basic Range Creation
use PhpStandardLibrary\Range\Range;
// Create a simple range (inclusive)
$range = new Range(1, 5);
// Iterate over the range
foreach ($range as $value) {
echo $value; // Outputs: 1, 2, 3, 4, 5
}
Key Classes to Know
Range: Core class for creating integer sequences.RangeIterator: Built-in iterator for looping.RangeException: Custom exceptions for invalid ranges.$range = new Range(1, 10, 2); // Step of 2 (1, 3, 5, 7, 9)
// Convert to array
$array = iterator_to_array($range);
// Use with Laravel Collections
collect($array)->filter(fn($n) => $n % 2 === 0); // Edge case: empty result
// Dynamic range based on user input
$start = request('start', 1);
$end = request('end', 100);
$range = new Range($start, $end);
// Validate before use
if ($range->isEmpty()) {
abort(400, 'Invalid range parameters');
}
// Batch processing with ranges
$batchSize = 100;
$totalItems = 1000;
$batches = new Range(1, ceil($totalItems / $batchSize));
foreach ($batches as $batch) {
ProcessBatchJob::dispatch($batch * $batchSize, $batchSize);
}
// Reverse iteration
$range = new Range(10, 1);
foreach ($range as $value) {
echo $value; // Outputs: 10, 9, ..., 1
}
// Custom step logic
$fibRange = new class(0, 100) implements \Iterator {
// Implement Iterator interface for Fibonacci-like sequences
};
Off-by-One Errors
Range(1, 5) includes both 1 and 5. Test edge cases:
$range = new Range(1, 1); // Single value: [1]
$range = new Range(5, 1); // Empty if step > 0
Step Direction
Range(5, 1, -1)) work but may surprise:
$range = new Range(1, 10, -1); // Empty (step direction mismatch)
Performance with Large Ranges
// Bad: $array = iterator_to_array(new Range(1, 1_000_000));
// Good: Process in chunks or use lazy evaluation
isEmpty() before iteration:
if ($range->isEmpty()) {
throw new \RuntimeException('Range is empty');
}
count() cautiously—it may load all values into memory for large ranges.Custom Range Logic
Override Range to add validation or metadata:
class ValidatedRange extends Range {
public function __construct(int $start, int $end, int $step = 1) {
if ($start > $end && $step > 0) {
throw new RangeException('Invalid range direction');
}
parent::__construct($start, $end, $step);
}
}
Laravel Service Provider Integration
Bind the Range class for dependency injection:
$this->app->bind(Range::class, function () {
return new ValidatedRange(...);
});
Testing Mock ranges in unit tests:
$mockRange = $this->createMock(Range::class);
$mockRange->method('current')->willReturn(42);
How can I help you explore Laravel packages today?