In this article on Range Function in PHP, I will explain the usage of the range() function. Also, some examples of creating arrays using the range() functions will be shown.

In order to create an array with elements in a specific range, we use the range() function. For instance, let our arrays have elements 1 to 10, or in another range such as 2, 4, 6,…, 20, and so on. As can be seen in the example, it takes three arguments: $start, $end, and $step. $start specifies the starting value of the range. Whereas, $end specifies the ending value of the range. Similarly, $step specifies the increment between values. When we don’t specify $step, it defaults to 1. The following code shows some examples of using the range() function.

// First, Create a range of integers from 1 to 10
$range1 = range(1, 10);
print_r($range1);

// Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )

// Then, Create a range of even numbers from 2 to 20
$range2 = range(2, 20, 2);
print_r($range2);

// Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 [5] => 12 [6] => 14 [7] => 16 [8] => 18 [9] => 20 )

// Next, Create a range of characters from 'a' to 'f'
$range3 = range('a', 'f');
print_r($range3);

// Output: Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )

// Also, Create a range of dates from '2022-01-01' to '2022-01-07'
$range4 = range('2022-01-01', '2022-01-07', '+1 day');
print_r($range4);

// Output: Array ( [0] => 2022-01-01 [1] => 2022-01-02 [2] => 2022-01-03 [3] => 2022-01-04 [4] => 2022-01-05 [5] => 2022-01-06 [6] => 2022-01-07 )

In the first example, we create a range of integers from 1 to 10. Likewise, in the second example, we create a range of even numbers from 2 to 20. Similarly, in the third example, we create a range of characters from ‘a’ to ‘f’. Lastly, in the fourth example, we create a range of dates from ‘2022-01-01’ to ‘2022-01-07’ with an increment of 1 day.

Also, note that the return value of the range() function is the array with these elements, and you can use it in conjunction with other array functions to manipulate the range of elements as needed.


Further Reading

Examples of Array Functions in PHP

Exploring PHP Arrays: Tips and Tricks

Basic Programs in PHP

Exploring Arrays in PHP

programmingempire

princites.com