Tutorialspoint.dev

PHP | range() Function

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:



  1. low: It will be the first value in the array generated by range() function.
  2. high: It will be the last value in the array generated by range() function.
  3. 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
  
// creating array with elements from 0 to 6
// using range function
$arr = range(0,6);
  
// printing elements of array
foreach ($arr as $a) {
      
    echo "$a ";
}
  
?>

/div>

Output:



0 1 2 3 4 5 6

Program 2:

<?php
  
// creating array with elements from 0 to 100
// with difference of 20 between consecutive 
// elements using range function
$arr = range(0,100,20);
  
// printing elements of array
foreach ($arr as $a) {
      
    echo "$a ";
}
  
?>

Output:

0 20 40 60 80 100

Program 3:

<?php
  
// creating array with elements from a to j
// using range function
$arr = range('a','j');
  
// printing elements of array
foreach ($arr as $a) {
      
    echo "$a ";
}
  
?>

Output:

a b c d e f g h i j

Program 4:

<?php
  
// creating array with elements from p to a
// in reverse order using range function
$arr = range('p','a');
  
// printing elements of array
foreach ($arr as $a) {
      
    echo "$a ";
}
  
?>

Output:

p o n m l k j i h g f e d c b a

Reference:
http://php.net/manual/en/function.range.php



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter