How to Use the PHP range Function to Create Arrays
This article explains how to use PHP’s built-in range()
function to easily generate arrays containing a sequential range of
numbers or letters. You will learn the syntax of the function, how to
generate ascending and descending sequences, how to create alphabetical
ranges, and how to use the step parameter to customize the increment
intervals between elements.
Understanding the range() Syntax
The range() function in PHP creates an array containing
a range of elements from a specified start point to an end point.
The syntax for the function is:
range(string|int|float $start, string|int|float $end, int|float $step = 1): array$start: The starting value of the sequence.$end: The ending value of the sequence.$step: (Optional) The increment used between values in the sequence. By default, this is1. It must be a positive number.
Generating Number Sequences
You can generate both ascending and descending arrays of integers or floats.
1. Ascending Number Range
To generate a simple sequence of numbers, provide the starting and ending integers:
$numbers = range(1, 5);
print_r($numbers);Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
2. Descending Number Range
If the start value is greater than the end value, PHP automatically generates a descending sequence:
$countdown = range(5, 1);
print_r($countdown);Output:
Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
Generating Letter Sequences
The range() function also supports single-character
strings to generate alphabetical sequences.
1. Lowercase Letter Range
Pass lowercase characters as the start and end parameters:
$letters = range('a', 'e');
print_r($letters);Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
2. Uppercase and Descending Letter Range
You can also generate uppercase sequences, as well as reverse-order letter sequences:
$reverse_letters = range('Z', 'V');
print_r($reverse_letters);Output:
Array
(
[0] => Z
[1] => Y
[2] => X
[3] => W
[4] => V
)
Using the Step Parameter
The third parameter, $step, allows you to define the gap
between each value in the sequence.
1. Step with Numbers
To get only even numbers between 0 and 10, set the step to
2:
$even_numbers = range(0, 10, 2);
print_r($even_numbers);Output:
Array
(
[0] => 0
[1] => 2
[2] => 4
[3] => 6
[4] => 8
[5] => 10
)
2. Step with Decimals (Float)
You can use float values for the step parameter to create sequences with decimal increments:
$decimals = range(0, 1.5, 0.5);
print_r($decimals);Output:
Array
(
[0] => 0
[1] => 0.5
[2] => 1
[3] => 1.5
)
3. Step with Letters
The step parameter also works with character sequences. For example, to select every second letter:
$spaced_letters = range('a', 'g', 2);
print_r($spaced_letters);Output:
Array
(
[0] => a
[1] => c
[2] => e
[3] => g
)