Home / Create an array containing a range of numbers or letters with PHP

Create an array containing a range of numbers or letters with PHP

Here’s another PHP function I discovered the other day which you may find useful. It’s called "range" and is used to create an array containing a range of numbers or letters. This is different from array_fill which creates an array with a number of the same elements and which I covered in my "Intialise an array in PHP with default values" post.

Create a sequence from 1 to 5

The range() function takes 2 required parameters to specify the range start and end, and an optional 3rd parameter which specifies how many numbers or letters to increment between each in the sequence created.

For example, to create an array filled with numbers 1 to 5 do this:

$values = range(1, 5);

Doing print_r($values) would output this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Create a sequence from 5 to 1

The order of the range can also be reversed by putting the higher number first and the lower number second like so:

$values = range(5, 1);

The print_r output would be:

Array
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

Create a sequence from 1 to 10, stepping 2 each time

By passing the optional third "step" parameter the sequence will increment by this amount instead of the default 1. This next example produces an array of numbers from 1 to 10 stepping 2 each time (i.e. 1, 3, 5 etc).

$values = range(1, 10, 2);

And the print_r output:

Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 7
    [4] => 9
)

Create a sequence of letters

If letters are specified instead of numbers then the sequence created is a range of letters. For example to create an array containing all the lower case letters of the alphabet, do this:

$letters = range('a', 'z');

The same reverse order and stepping rules apply with passing letters, so to get the letters from z to r in reverse order, stepping two letters at a time, do this:

$letters = range('z', 'r', 2);

And print_r($letters) would be:

Array
(
    [0] => z
    [1] => x
    [2] => v
    [3] => t
    [4] => r
)