Ranges

suggest change

A range is a sequence of values between a start and an end: the numbers 1 to 10, the letters a to z, every day in March. PHP has no range literal like 1..10 in Ruby or Kotlin. Instead you get:

This article covers all of them, plus the edge cases of range() that changed in PHP 8.3. All examples were run with PHP 8.5.

range() basics

range($start, $end, $step = 1) returns an array with every value from $start to $end. Both ends are included:

<?php
echo implode(' ', range(1, 5)), "\n";
echo implode(' ', range(5, 1)), "\n";
echo implode(' ', range(0, 10, 3)), "\n";
echo implode(' ', range(-2, 2)), "\n";

Output:

1 2 3 4 5
5 4 3 2 1
0 3 6 9
-2 -1 0 1 2

Things to notice:

For a descending range you can give the step as positive or negative, the result is the same:

<?php
echo implode(',', range(10, 0, 5)), "\n";
echo implode(',', range(10, 0, -5)), "\n";

Output:

10,5,0
10,5,0

The Initializing an Array article shows range() side by side with a manual loop.

Invalid arguments throw ValueError

Since PHP 8.3, range() checks its arguments and throws ValueError for ones that make no sense. Older versions silently returned odd results instead:

<?php
$bad = [
    fn() => range(1, 10, 0),
    fn() => range(1, 10, -2),
    fn() => range(1, 3, 5),
    fn() => range(1, INF),
];
foreach ($bad as $f) {
    try {
        $f();
    } catch (ValueError $e) {
        echo $e->getMessage(), "\n";
    }
}

Output:

range(): Argument #3 ($step) cannot be 0
range(): Argument #3 ($step) must be greater than 0 for increasing ranges
range(): Argument #3 ($step) must be less than the range spanned by argument #1 ($start) and argument #2 ($end)
range(): Argument #2 ($end) must be a finite number, INF provided

The third one catches people out: a step larger than the whole span is an error, not a one-element array. If the step comes from user input (for example "show every Nth page"), check it or catch the ValueError.

Float ranges

If the start, end or step is a float, the elements are floats:

<?php
var_dump(range(0, 1, 0.5));
echo json_encode(range(0.1, 0.5, 0.1)), "\n";

Output:

array(3) {
  [0]=>
  float(0)
  [1]=>
  float(0.5)
  [2]=>
  float(1)
}
[0.1,0.2,0.30000000000000004,0.4,0.5]

0.1 has no exact binary representation, so the values are only close to what you wrote. Worse, the number of elements can come out one short. range() works out how many elements to make by dividing the span by the step, and 0.3 / 0.1 is 2.9999999999999996, not 3:

<?php
// Adding the step over and over: rounding errors pile up
$loop = [];
for ($x = 0.0; $x <= 0.3; $x += 0.1) {
    $loop[] = $x;
}
echo "loop:    ", json_encode($loop), "\n";

// range() has the same problem with the element count
echo "range(): ", json_encode(range(0.0, 0.3, 0.1)), "\n";

// Integer counter, converted at the end
$exact = array_map(fn(int $i) => $i / 10, range(0, 3));
echo "ints:    ", json_encode($exact), "\n";

Output:

loop:    [0,0.1,0.2]
range(): [0,0.1,0.2]
ints:    [0,0.1,0.2,0.3]

The end value 0.3 is missing from the first two results. The reliable approach is the last one: make a range of integers and convert each one. See Float for more on floating point precision.

Character ranges

When both arguments are single-byte strings, range() steps through characters by their byte value:

<?php
echo implode(' ', range('a', 'f')), "\n";
echo implode(' ', range('Z', 'U')), "\n";
echo implode(' ', range('a', 'z', 5)), "\n";
echo implode(' ', range('A', 'z')), "\n";

Output:

a b c d e f
Z Y X W V U
a f k p u z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z

The last line shows a trap: range('A', 'z') is not "all letters". In ASCII there are six punctuation characters between Z and a. For all letters, merge two ranges:

<?php
$letters = array_merge(range('A', 'Z'), range('a', 'z'));
echo count($letters), "\n";

Output:

52

Only the first byte of each string is used. range('aa', 'cc') doesn't produce aa, ab, ..., it emits warnings and gives a, b, c:

Warning: range(): Argument #1 ($start) must be a single byte, subsequent bytes are ignored in ...
Warning: range(): Argument #2 ($end) must be a single byte, subsequent bytes are ignored in ...

Multibyte UTF-8 characters such as ą or é don't work for the same reason. For those, build the list yourself or use IntlChar/mb_chr() over a range of code points.

Numeric strings

Digits in strings are another trap. A one-character string like '1' is a single byte, so you get a character range of strings. A longer numeric string like '12' is treated as a number:

<?php
var_dump(range('1', '3')[0]);   // single bytes: a character range
var_dump(range('8', '12')[0]);  // multi-digit numeric strings: numbers
var_dump(range((int) '1', (int) '3')[0]);

Output:

string(1) "1"
int(8)
int(1)

Values from $_GET, $argv or a CSV file are always strings. Cast them to int before passing them to range() so you always get integers. Mixing a letter and a number (range('a', 3)) emits a warning and treats the letter as 0.

Lazy ranges with generators

range() builds the whole array before your loop starts. For big ranges that costs a lot of memory. A generator produces the same values one at a time:

<?php
/**
 * Lazy inclusive range: yields values one at a time instead of building an array.
 */
function xrange(int $start, int $end, int $step = 1): Generator
{
    if ($step <= 0) {
        throw new ValueError('step must be positive');
    }
    if ($start <= $end) {
        for ($i = $start; $i <= $end; $i += $step) {
            yield $i;
        }
    } else {
        for ($i = $start; $i >= $end; $i -= $step) {
            yield $i;
        }
    }
}

foreach (xrange(1, 10, 4) as $n) {
    echo $n, ' ';
}
echo "\n";
echo implode(' ', iterator_to_array(xrange(5, 1))), "\n";

Output:

1 5 9
5 4 3 2 1

To see the difference, sum the numbers from 1 to 1,000,000 three ways and look at peak memory usage:

<?php
function xrange(int $start, int $end): Generator
{
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

$mode = $argv[1];
$sum = 0;
if ($mode === 'range') {
    foreach (range(1, 1_000_000) as $n) {
        $sum += $n;
    }
} elseif ($mode === 'xrange') {
    foreach (xrange(1, 1_000_000) as $n) {
        $sum += $n;
    }
} else {
    for ($n = 1; $n <= 1_000_000; $n++) {
        $sum += $n;
    }
}
printf("%-6s sum=%d peak=%.1f MB\n", $mode, $sum, memory_get_peak_usage() / 1024 / 1024);

Output of php sum.php range, php sum.php xrange and php sum.php for:

range  sum=500000500000 peak=18.5 MB
xrange sum=500000500000 peak=0.5 MB
for    sum=500000500000 peak=0.5 MB

The generator uses no more memory than a plain for loop. Use range() when you need an actual array (to index, slice, shuffle or pass to array functions) and the range is small. For just looping over numbers, a for loop or a generator is enough.

A Range class

When a range is a value in your domain (allowed ports, page numbers, an age bracket) it helps to wrap it in a class. This one is immutable and lazy, and it works with foreach and count():

<?php
/**
 * Immutable, lazy, inclusive integer range.
 *
 * @implements IteratorAggregate<int, int>
 */
final readonly class IntRange implements IteratorAggregate, Countable
{
    public function __construct(
        public int $start,
        public int $end,
        public int $step = 1,
    ) {
        if ($step <= 0) {
            throw new ValueError('step must be greater than 0');
        }
        if ($end < $start) {
            throw new ValueError("end ($end) must not be less than start ($start)");
        }
    }

    public function contains(int $value): bool
    {
        return $value >= $this->start
            && $value <= $this->end
            && ($value - $this->start) % $this->step === 0;
    }

    public function count(): int
    {
        return intdiv($this->end - $this->start, $this->step) + 1;
    }

    public function getIterator(): Generator
    {
        for ($i = $this->start; $i <= $this->end; $i += $this->step) {
            yield $i;
        }
    }

    public function overlaps(IntRange $other): bool
    {
        return $this->start <= $other->end && $other->start <= $this->end;
    }

    public function toArray(): array
    {
        return iterator_to_array($this, false);
    }

    public function __toString(): string
    {
        $s = "[{$this->start}..{$this->end}]";
        return $this->step === 1 ? $s : "$s step {$this->step}";
    }
}

$r = new IntRange(10, 30, 5);
echo $r, "\n";
echo "count: ", count($r), "\n";
echo "values: ", implode(', ', $r->toArray()), "\n";
var_dump($r->contains(20), $r->contains(22), $r->contains(35));

$sum = 0;
foreach (new IntRange(1, 100) as $n) {
    $sum += $n;
}
echo "sum 1..100: $sum\n";

$a = new IntRange(1, 10);
var_dump($a->overlaps(new IntRange(10, 20)), $a->overlaps(new IntRange(11, 20)));

$big = new IntRange(0, PHP_INT_MAX - 1);
echo "big count: ", count($big), "\n";

try {
    new IntRange(5, 1);
} catch (ValueError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

Output:

[10..30] step 5
count: 5
values: 10, 15, 20, 25, 30
bool(true)
bool(false)
bool(false)
sum 1..100: 5050
bool(true)
bool(false)
big count: 9223372036854775807
ValueError: end (1) must not be less than start (5)

contains() and count() are computed with arithmetic, so they are instant even for a range with 9 quintillion elements. With range() that range couldn't be built at all.

Checking if a value is in a range

To test whether a number is between two bounds, compare it. Don't build an array:

<?php
function inRange(int|float $value, int|float $min, int|float $max): bool
{
    return $value >= $min && $value <= $max;
}

function clampValue(int|float $value, int|float $min, int|float $max): int|float
{
    return max($min, min($max, $value));
}

var_dump(inRange(5, 1, 10));
var_dump(inRange(10, 1, 10));
var_dump(inRange(10.5, 1, 10));

echo clampValue(150, 0, 100), "\n";
echo clampValue(-3, 0, 100), "\n";
echo clampValue(42, 0, 100), "\n";

// Don't do this: builds a 1,000,001-element array just to answer yes/no
var_dump(in_array(500_000, range(0, 1_000_000)));

Output:

bool(true)
bool(true)
bool(false)
100
0
42
bool(true)

The in_array(range()) version gives the right answer but allocates about 16 MB and searches the array element by element. It also misses non-integers: 10.5 is between 1 and 20, but it isn't an element of range(1, 20).

PHP 8.5 has no built-in clamp() function, so max($min, min($max, $value)) is the usual idiom.

For validating input, filter_var() with min_range and max_range checks the type and the bounds in one step, see Validating An Integer Falls In A Range.

Mapping ranges to values with match

To map a value to a bucket depending on which range it falls in, use match (true). Arms are checked from top to bottom, so each arm only needs the lower bound:

<?php
function grade(int $score): string
{
    return match (true) {
        $score < 0 || $score > 100 => throw new RangeException("score out of range: $score"),
        $score >= 90 => 'A',
        $score >= 80 => 'B',
        $score >= 70 => 'C',
        $score >= 60 => 'D',
        default      => 'F',
    };
}

foreach ([95, 80, 61, 12, 101] as $s) {
    try {
        echo $s, ' => ', grade($s), "\n";
    } catch (RangeException $e) {
        echo $e->getMessage(), "\n";
    }
}

Output:

95 => A
80 => B
61 => D
12 => F
101 => score out of range: 101

RangeException is the SPL exception meant for "value out of the valid range" errors.

Slicing part of an array or string

Taking a range of elements out of an array is done with array_slice($array, $offset, $length). Note that the third argument is a length, not an end index. A negative offset counts from the end, and a negative length leaves out that many elements at the end:

<?php
$letters = range('a', 'j');

echo implode('', array_slice($letters, 2, 3)), "\n";   // indexes 2..4
echo implode('', array_slice($letters, -3)), "\n";     // last 3
echo implode('', array_slice($letters, 1, -1)), "\n";  // drop first and last

// Inclusive "from..to" helper on top of array_slice
function sliceRange(array $a, int $from, int $to): array
{
    return array_slice($a, $from, $to - $from + 1);
}
echo implode('', sliceRange($letters, 3, 6)), "\n";

// Same idea for strings
echo substr('Hello, World', 7, 5), "\n";

Output:

cde
hij
bcdefghi
defg
World

substr() works on bytes. For UTF-8 text use mb_substr(), which has the same arguments but counts characters.

Building arrays from ranges

range() combines well with other array functions to make lookup tables:

<?php
// Spreadsheet-style column letters => numbers
$columns = array_flip(range('A', 'Z'));
echo $columns['A'], ' ', $columns['C'], ' ', $columns['Z'], "\n";

// Build keys and values from ranges
$squares = array_combine(range(1, 5), array_map(fn($n) => $n ** 2, range(1, 5)));
print_r($squares);

// A random 8-character code from a custom alphabet
$alphabet = implode('', array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9)));
$rng = new Random\Randomizer();
echo strlen($rng->getBytesFromString($alphabet, 8)), "\n";

Output:

0 2 25
Array
(
    [1] => 1
    [2] => 4
    [3] => 9
    [4] => 16
    [5] => 25
)
8

Randomizer::getBytesFromString() (PHP 8.3+) picks random characters from the given string, so with a range-built alphabet you get a random code in one call.

Inclusive or exclusive?

Different PHP functions treat the end of a range differently, and it's a common source of off-by-one bugs:

<?php
// random_int() bounds are inclusive on both ends
$seen = [];
for ($i = 0; $i < 1000; $i++) {
    $seen[random_int(1, 3)] = true;
}
ksort($seen);
echo implode(',', array_keys($seen)), "\n";

// Randomizer::getFloat() lets you choose which ends are included
$rng = new Random\Randomizer();
$f = $rng->getFloat(0.0, 1.0, Random\IntervalBoundary::ClosedOpen); // [0, 1)
var_dump($f >= 0.0 && $f < 1.0);

Output:

1,2,3
bool(true)
Function Start End
range($a, $b) included included
random_int($a, $b), mt_rand($a, $b) included included
filter_var() with min_range/max_range included included
array_slice($arr, $offset, $length) included given as a length
substr($s, $offset, $length) included given as a length
new DatePeriod($start, $interval, $end) included excluded (unless INCLUDE_END_DATE)
Randomizer::getFloat() configurable with IntervalBoundary configurable

Date ranges with DatePeriod

range() only works with numbers and characters. For dates, use DatePeriod, which iterates from a start date in steps of a DateInterval:

<?php
$start = new DateTimeImmutable('2026-03-27');
$end   = new DateTimeImmutable('2026-04-02');

// End date is excluded by default
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach ($period as $day) {
    echo $day->format('D Y-m-d'), "\n";
}

echo "---\n";
// INCLUDE_END_DATE makes it inclusive, like range()
$weekly = new DatePeriod($start, new DateInterval('P1W'), new DateTimeImmutable('2026-04-24'),
    DatePeriod::INCLUDE_END_DATE);
foreach ($weekly as $d) {
    echo $d->format('Y-m-d'), "\n";
}

echo "---\n";
// From an ISO 8601 string (PHP 8.3+): 3 recurrences after the start date
$p = DatePeriod::createFromISO8601String('R3/2026-01-31T00:00:00Z/P1M');
foreach ($p as $d) {
    echo $d->format('Y-m-d'), "\n";
}

Output:

Fri 2026-03-27
Sat 2026-03-28
Sun 2026-03-29
Mon 2026-03-30
Tue 2026-03-31
Wed 2026-04-01
---
2026-03-27
2026-04-03
2026-04-10
2026-04-17
2026-04-24
---
2026-01-31
2026-03-03
2026-04-03
2026-05-03

Two things to watch out for:

DatePeriod uses the same immutable classes as the rest of the date API, see Add or Subtract Date Intervals.

Summary

Need Use
Small array of consecutive numbers or letters range($start, $end, $step)
Loop over a large range of numbers for loop or a generator
Float steps without rounding surprises integer range() + array_map() dividing each value
A range as a value with contains(), count() a small immutable class with IteratorAggregate and Countable
Is $x between $min and $max $x >= $min && $x <= $max
Force a value into bounds max($min, min($max, $x))
Validate input is an integer in bounds filter_var() with min_range / max_range
Part of an array or string array_slice(), substr(), mb_substr()
Sequence of dates DatePeriod

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents