PHP Reference ยท Array Functions
PHP range() function
Reference for PHP range(): create arrays of numbers or letters, use a step, count down, work with floats, and handle the errors PHP 8.3 introduced.
range() creates an array containing a sequence of values from a start to an end, both included. It works with integers, floats and single characters, and an optional step sets the distance between values.
It builds the whole array in memory. For a very long loop, a plain for loop or a generator uses far less memory.
<?php echo implode(",", range(1, 5)); // 1,2,3,4,5 echo implode(",", range("a", "e")); // a,b,c,d,e
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
range(string|int|float $start, string|int|float $end, int|float $step = 1): array
| Name | Description |
|---|---|
$start |
First value of the sequence. |
$end |
Last value. It is included only if the step lands exactly on it. |
$step |
Distance between values. Its sign is ignored; the direction comes from $start and $end. Default 1. |
Return value: an array of the generated values, starting at $start.
Errors: a ValueError is thrown (PHP 8.3+) when $step is 0, or is larger than the distance between $start and $end.
Usage notes
- Counting down: just put the larger number first.
range(5, 1)gives5,4,3,2,1. You can pass a positive step for this. - Characters: with single-byte letters, the sequence follows byte values.
range("a", "z")is the lowercase alphabet; uppercase and lowercase are not mixed. - Types: integers produce integers, floats produce floats. PHP 8.3 made the rules more consistent, for example numeric strings behave as numbers.
- Floating-point steps can accumulate error. Treat the exact float values with care, and compare them with a tolerance.
- The end may be skipped:
range(0, 10, 3)is0,3,6,9; 10 is not reached. - Memory:
range(1, 1000000)allocates a million-element array. Use aforeachover a generator for lazy sequences. - Combine with
array_map()orarray_sum()for compact computations.
Related
array_fill(),array_map(),array_sum(),for- Lessons: Arrays, Array functions