The range()
function creates an array of numbers between the first parameter
and the second parameter two.
PHP range() Function has the following syntax.
range(low,high,step)
Parameter | Is Required | Description |
---|---|---|
low | Required. | Lowest value of the array |
high | Required. | Highest value of the array |
step | Optional. | Increment used in the range. Default is 1. |
If the low parameter is higher than the high parameter, the range array will be from high to low.
This function returns an array of elements from low to high.
Use range() function to create array
<?PHP $numbers = range(1,10); print_r($numbers); ?>
The code above generates the following result.
The third parameter from range()
function sets the step.
It can either be an integer or a floating-point number.
<?PHP $numbers = range(1, 10, 2); print_r($numbers); print "\n"; $numbers = range(1, 10, 3); print_r($numbers); print "\n"; $numbers = range(10, 100, 10); print_r($numbers); print "\n"; $numbers = range(1, 10, 1.2); print_r($numbers); ?>
The code above generates the following result.
The third parameter should always be positive.
If the first parameter is higher than the second parameter, we will get an array counting down.
<?PHP $values = range(100, 0, 10); print_r($values); //We can use range() to create arrays of characters: $values = range("a", "z", 1); print_r($values); print "\n"; $values = range("z", "a", 2); print_r($values); ?>
The code above generates the following result.
Create an array containing a range of elements from "0" to "5":
<?php $number = range(0,5); print_r ($number); ?>
The code above generates the following result.
Return an array of elements from "0" to "50" and increment by 10.
<?php $number = range(0,50,10); print_r ($number); ?>
The code above generates the following result.
Using letters - return an array of elements from "a" to "d"
<?php $letter = range("a","d"); print_r ($letter); ?>
The code above generates the following result.