The array_range() function in PHP (implemented using range()) is used to generate an array containing values between a specified start and end point. An optional step value allows control over how values increase or decrease.
The basic syntax of the range function is:
// Generates an array from start to end with optional step
range(start, end, step);
Adjust the values below to see how the array is generated instantly!
// Generate numbers from 1 to 5
<?php
$array = range(1, 5);
print_r($array);
?>
This creates an array containing five elements: 1, 2, 3, 4, and 5.
// Generate numbers from 1 to 10 with step of 2
<?php
$array = range(1, 10, 2);
print_r($array);
?>
The step value of 2 skips every alternate number, resulting in: 1, 3, 5, 7, and 9.
Imagine the function as a number line generator. You define where to start, where to stop, and how many steps to jump each time.
// Visualizing a reverse range using a negative step
<?php
$reverse = range(10, 1, -1);
print_r($reverse);
?>
range() for clean and readable loops.range().