PHP range is an inbuilt Function in PHP. It creates an array containing a range of elements of any kind such as integer or alphabets. It creates an array within the input range (from low to high). In this article, we will discuss the PHP range Function. Also, we will discuss a few examples to demonstrate it’s usage.
array range(low, high, step = 1)
The PHP range Function expects three parameters. Two parameters are mandatory, while the third one is optional.
- $low: It is the first value in the array you need. It is mandatory to pass this parameter.
- $high: It refers to the last value in the array you require. Also, it is a mandatory parameter.
- $step: It refers to the increment size you need in the array. It is optional to pass with the default value as 1.
The PHP range Function returns an array of elements from low to high. Also, the step size of the array can be changed by passing the step parameter.
Let’s discuss a few examples of using range Function
Example 1: Integer Array
<?php $testArray = range(1, 5); print_r($testArray); /* Array (  => 1  => 2  => 3  => 4  => 5 ) */ ?>
In the above article, the function returns an array from 1 to 5. This is because, the $low parameter is set to 1 and the $high parameter is set to 5. Since, the $step parameter is not passed, the default value 1 is used.
Example 2: Custom Step Size
You can set a custom step size by passing the $step parameter.
<?php $testArray = range(1, 10, 2); print_r($testArray); /* Array (  => 1  => 3  => 5  => 7  => 9 ) */ ?>
In the above example, the $low parameter is 1 and the $high parameter is 10. However, the $step parameter is 2 and the function returns an array from 1 to 9 with increment size as 2.
Example 3: Reverse Array
Also, you can create an array with reverse order using PHP range Function.
<?php $testArray = range(5, 1); print_r($testArray); /* Array (  => 5  => 4  => 3  => 2  => 1 ) */ ?>
Example 4: Alphabets Array
You can also pass alphabets in $low and $high parameter. The function returns an array with alphabets.
<?php $testArray = range('a', 'e'); print_r($testArray); /* Array (  => a  => b  => c  => d  => e ) */ ?>
Example 5: Reverse Alphabets with Step Size
Similarly, you can pass step size and get alphabets in reverse order.
<?php $testArray = range('m', 'c', 2); print_r($testArray); /* Array (  => m  => k  => i  => g  => e  => c ) */ ?>
Vishesh is currently working as a Senior Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.