PHP

πŸ”’ PHP range() Function: Generating Sequences of Elements

The range() function in PHP creates an array containing a range of elements such as sequential numbers or alphabetical character sequences.

  • Return Value: range() returns an indexed array of elements from the low starting value to the high ending value, inclusive.

πŸ› οΈ Basic Usage & Parameter Syntax

You can generate integer ranges, character sequences, or use custom step increments:

PHP
// 1. Numeric sequence (0 to 5)
$numbers = range(0, 5);
print_r($numbers); 
// Outputs: [0, 1, 2, 3, 4, 5]

// 2. Character sequence ('a' to 'e')
$letters = range('a', 'e');
print_r($letters); 
// Outputs: ['a', 'b', 'c', 'd', 'e']

// 3. Step increment (0 to 10 with step 2)
$evenNumbers = range(0, 10, 2);
print_r($evenNumbers); 
// Outputs: [0, 2, 4, 6, 8, 10]

πŸ”„ Decrementing & Reverse Sequences

If the starting parameter is higher than the ending parameter, range() automatically creates a descending sequence:

PHP
// Descending numbers (10 to 1)
$countdown = range(10, 1);
print_r($countdown);
// Outputs: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

// Reverse character range ('z' to 'w')
$reverseAlphabet = range('z', 'w');
print_r($reverseAlphabet);
// Outputs: ['z', 'y', 'x', 'w']

πŸ“‹ Key Rules & Behaviors

  • 1. Three Parameters: Syntax is range(start, end, step) where step defaults to 1.
  • 2. String Limits: When generating letter ranges, only the first character of string arguments is used (e.g., `'aa'` is treated as `'a'`).
  • 3. Float Steps: In PHP 8.3+, passing invalid or zero step values generates a ValueError exception.

πŸ“Š range() Function Specifications

Parameter Type Required? Description
start String / Int / Float βœ… Yes First value of the generated sequence
end String / Int / Float βœ… Yes Final value of the generated sequence
step Int / Float ❌ Optional Increment/decrement value (default is 1)
  • πŸ“ Short Summary

  • range() provides a quick way to create sequential arrays of numbers or letters.
  • It supports custom step values for skipping intervals like even or odd numbers.
  • It automatically detects whether to generate ascending or descending sequences based on parameter values.