PHP Function Reference

PHP range() Function



The PHP range() function creates an array containing a range of elements. The syntax for using this function is given below:

Syntax

range(start, end, step)

Parameters

start Required. Specify first value of the sequence.
end Required. Specify last value of the sequence.
step Optional. Specify a step value. It is used as the increment between elements in the sequence. Default to 1.

Return Value

Returns an array of elements from start to end, inclusive.

Exceptions

NA.

Example:

The example below shows the usage of range() function.

<?php
$Arr1 = range(1, 5);
//with step size 10
$Arr2 = range(10, 50, 10);
//with step size -1
$Arr3 = range(5, 1, -1);

//displaying result
print_r($Arr1);
echo "\n";
print_r($Arr2);
echo "\n";
print_r($Arr3);
?>

The output of the above code will be:

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

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)

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

Example:

Consider the example below where range() function is used to create character sequences.

<?php
$Arr1 = range('a', 'e');
$Arr2 = range('e', 'a');

//displaying result
print_r($Arr1);
echo "\n";
print_r($Arr2);
?>

The output of the above code will be:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)

Array
(
    [0] => e
    [1] => d
    [2] => c
    [3] => b
    [4] => a
)

❮ PHP Array Reference