The range() function is an inbuilt function in PHP which is used to create an array of elements of any kind such as integer, alphabets within a given range(from low to high) i.e, list’s first element is considered as low and last one is considered as high. Syntax:
array range(low, high, step)
Parameters: This function accepts three parameters as described below:
- low: It will be the first value in the array generated by range() function.
- high: It will be the last value in the array generated by range() function.
- step: It is used when the increment used in the range and it’s default value is 1.
Return Value: It returns an array of elements from low to high. Examples:
Input : range(0, 6)
Output : 0, 1, 2, 3, 4, 5, 6
Explanation: Here range() function print 0 to
6 because the parameter of range function is 0
as low and 6 as high. As the parameter step is
not passed, values in the array are incremented
by 1.
Input : range(0, 100, 10)
Output : 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
Explanation: Here range() function accepts
parameters as 0, 100, 10 which are values of low,
high, step respectively so it returns an array with
elements starting from 0 to 100 incremented by 10.
Below programs illustrate range() function in PHP: Program 1:
PHP
<?php
$arr = range(0,6);
foreach ( $arr as $a ) {
echo "$a " ;
}
?>
|
Output:
0 1 2 3 4 5 6
Time Complexity: O(1)
Auxiliary Space: O(1)
Program 2:
PHP
<?php
$arr = range(0,100,20);
foreach ( $arr as $a ) {
echo "$a " ;
}
?>
|
Output:
0 20 40 60 80 100
Time Complexity: O(1)
Auxiliary Space: O(1)
Program 3:
PHP
<?php
$arr = range( 'a' , 'j' );
foreach ( $arr as $a ) {
echo "$a " ;
}
?>
|
Output:
a b c d e f g h i j
Time Complexity: O(1)
Auxiliary Space: O(1)
Program 4:
PHP
<?php
$arr = range( 'p' , 'a' );
foreach ( $arr as $a ) {
echo "$a " ;
}
?>
|
Output:
p o n m l k j i h g f e d c b a
Time Complexity: O(n)
Auxiliary Space: O(1)
Reference: http://php.net/manual/en/function.range.php