range()
range() — Create an array containing a range of elements.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
Signature
range(string|int|float $start, string|int|float $end, int|float $step = 1): array
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $start | string|int|float | First value of the sequence. |
| $end | string|int|float | Last possible value of the sequence. |
| $step | int|float | step indicates by how much is the produced sequence progressed between values of the sequence. |
Return value
Returns a sequence of elements as an array with the first element being start going up to end, with each value of the sequence being step values apart. The last element of the returned array is either end or the previous element of the sequence, depending on the value of step. If both start and end are strings, and step is int the produced array will be a sequence of bytes, generally latin ASCII characters. If at least one of start, end, or step is float the produced array will be a sequence of float. Otherwise, the produced array will be a sequence of int.
Example
A runnable snippet:
echo implode(', ', range(0, 12)), PHP_EOL; echo implode(', ', range(0, 100, 10)), PHP_EOL; echo implode(', ', range('a', 'i')), PHP_EOL; echo implode(', ', range('c', 'a')), PHP_EOL; echo implode(', ', range('A', 'z')), PHP_EOL;
Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 a, b, c, d, e, f, g, h, i c, b, a 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
Changelog
| Version | Change |
|---|---|
| 8.3.0 | If both start and end are strings then range() will now always produce an array of bytes. Previously if one of the boundary values was a numeric string, then the other boundary value was implicitly cast to int. |
| 8.3.0 | An E_WARNING is now emitted if start or end is a string that is implicitly cast to int because the other boundary value is a number. |
| 8.3.0 | An E_WARNING is now emitted if start or end is a non-numeric string with more than one byte. |
| 8.3.0 | An E_WARNING is now emitted if start or end is the empty string. |
| 8.3.0 | If step is a float with no fractional part, it will be interpreted as an int. |
| 8.3.0 | A ValueError is now thrown if step is negative when producing an increasing range. |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page range() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.