PHP range() Function
Topic: PHP Array ReferencePrev|Next
Description
The range()
function creates an array containing a range of elements.
The following table summarizes the technical details of this function.
Return Value: | Returns an array of elements from start to end, inclusive. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the range()
function is given with:
The following example shows the range()
function in action.
Example
Run this code »<?php
// Creating range of numbers
$numbers = range(0, 5);
print_r($numbers);
?>
Parameters
The range()
function accepts the following parameters.
Parameter | Description |
---|---|
start | Required. Specifies the first value of the sequence. |
end | Required. Specifies the end value of the sequence. |
step | Optional. Specifies the increment to be used between the elements in the sequence. It should always be a positive number. If not specified, step will default to 1. |
More Examples
Here're some more examples showing how range()
function actually works:
The following example demonstrates how to get the sequence of characters between "a" to "z".
Example
Run this code »<?php
// Creating range of letters
$letters = range("a", "z");
// Printing each value using loop
foreach($letters as $letter){
echo $letter . "<br>";
}
?>
Note: Character sequence values are limited to a length of one. If string of length greater than one is entered, only the first character is used (e.g., if "hp" is specified "h" will be used).
The following example creates a range of numbers using a floating-point number step.
Example
Run this code »<?php
// Creating range of numbers using step
$numbers = range(1, 10, 0.5);
// Printing each value using loop
foreach($numbers as $number){
echo $number . "<br>";
}
?>