← Back to Chapters

PHP array_range() Function

? PHP array_range() Function

? Quick Overview

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.

? Key Concepts

  • Sequential Data – Automatically creates ordered arrays.
  • Flexible Step – Supports positive and negative step values.
  • Numeric & Character Ranges – Works with numbers and letters.

? Syntax / Theory

The basic syntax of the range function is:

// Generates an array from start to end with optional step
range(start, end, step);

? Live Range Playground

Adjust the values below to see how the array is generated instantly!

 

? Code Example 1: Basic Range

? View Code Example
// Generate numbers from 1 to 5
<?php
$array = range(1, 5);
print_r($array);
?>

? Output Explanation

This creates an array containing five elements: 1, 2, 3, 4, and 5.

? Code Example 2: Range with Step

? View Code Example
// Generate numbers from 1 to 10 with step of 2
<?php
$array = range(1, 10, 2);
print_r($array);
?>

? Output Explanation

The step value of 2 skips every alternate number, resulting in: 1, 3, 5, 7, and 9.

? Interactive Understanding

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);
?>

? Use Cases

  • Creating pagination numbers
  • Generating loop counters
  • Building dropdown values
  • Producing test datasets

✅ Tips & Best Practices

  • Use range() for clean and readable loops.
  • Negative steps are ideal for countdown logic.
  • Ensure step direction matches start and end values.

? Try It Yourself

  • Create a range from 10 to 50 with a step of 5.
  • Generate letters from "a" to "z" using range().
  • Build a countdown timer array from 20 to 0.