What is the range() method in PHP?
The range method can be used to create a sequence of numbers as an array.
Syntax
range(string|int|float $start, string|int|float $end, int|float $step = 1): array
Arguments
-
start: Starting value of the array. Thestartvalue is included. -
end: End value of the array. Theendvalue is included. -
step: The increment value between elements. It is an optional value, and the default value is1.
Points to note
- If the
startis greater than theend, then the range will be in decrementing order. For example, consider:
start = 10
end = 6
step = 2
range(10, 6, 2) => [10, 8, 6]
- We can use the
rangemethod to generate character sequences. The character sequence range is limited to a length of one. If a length greater than one is given, then only the first character is used.
Example
<?php$numbers = range(0,2);echo "Start: 0, End: 3, Step: 1\n";printArray($numbers);$numbers = range(1.5, 3.3, 0.5);echo "Start: 1.5, End: 3.3, Step: 0.5\n";printArray($numbers);$characters = range('a', 'e', 2);echo "Start: a, End: e, Step: 2\n";printArray($characters);function printArray($array){echo "The array is \n";print_r($array);echo "\n";}?>
In the code above, we used the range method to generate a sequence of numbers and characters.