ZetCode

PHP range Function

last modified May 21, 2025

In this article, we explore PHP's range function, a convenient way to create arrays containing a range of elements. The range function generates an array of elements between a start and end value, with optional step between elements.

The range function is particularly useful when you need to quickly generate sequences of numbers or characters without writing manual loops. It's commonly used for creating test data, initializing arrays, and generating sequences for iteration.

The advantages of PHP's range function are:

By using range, developers can write cleaner, more expressive code when working with sequences of values in PHP.

Basic range syntax

The range function accepts two mandatory parameters (start and end) and one optional parameter (step).

range(mixed $start, mixed $end[, int $step = 1]): array

The start is parameter is inclusive, while the end parameter is exclusive. The step parameter defines the increment between elements in the generated array. The syntax is as follows:

basic_range.php
<?php

declare(strict_types=1);

// Numeric ranges
$numbers = range(1, 5);
print_r($numbers);

// With step value
$evenNumbers = range(0, 10, 2);
print_r($evenNumbers);

// Descending range
$descending = range(5, 1);
print_r($descending);

// Float ranges
$floatRange = range(0, 1, 0.2);
print_r($floatRange);

// Character ranges
$letters = range('a', 'e');
print_r($letters);

// Character range with steps
$skipLetters = range('a', 'z', 2);
print_r($skipLetters);

// Using variables
$start = 10;
$end = 15;
$dynamicRange = range($start, $end);
print_r($dynamicRange);

This demonstrates the basic usage of range with different types of values. The function handles both ascending and descending ranges, and works with integer, float, and character sequences. The step parameter controls the increment between values.

Practical use cases

The range function has many practical applications in PHP development. Here are some common scenarios where it proves particularly useful.

practical_uses.php
<?php

declare(strict_types=1);

// 1. Generating test data
$testUsers = array_map(function($id) {
    return [
        'id' => $id,
        'name' => 'User ' . $id,
        'email' => "user$id@example.com"
    ];
}, range(1, 5));

print_r($testUsers);

// 2. Creating dropdown options
function generateYearOptions(int $start, int $end): string {
    $options = array_map(function($year) {
        return '<option value="' . $year . '">' . $year . '</option>';
    }, range($start, $end));

    return implode("\n", $options);
}

echo 'Year options:' . "\n" . generateYearOptions(2020, 2025) . "\n";

// 3. Pagination controls
function generatePagination(int $current, int $totalPages): string {
    $visiblePages = 5;
    $start = max(1, $current - 2);
    $end = min($totalPages, $start + $visiblePages - 1);

    $pages = range($start, $end);
    $links = array_map(function($page) use ($current) {
        $active = $page === $current ? ' class="active"' : '';
        return '<li' . $active . '><a href="?page=' . $page . '">' . $page . '</a></li>';
    }, $pages);

    return '<ul class="pagination">' . implode('', $links) . '</ul>';
}

echo 'Pagination:' . "\n" . generatePagination(3, 10) . "\n";

// 4. Alphabetical filters
$alphabet = range('A', 'Z');
$alphaFilters = array_map(function($letter) {
    return '<a href="/items/' . $letter . '">' . $letter . '</a>';
}, $alphabet);

echo 'Alphabetical filters:' . "\n" . implode(' | ', $alphaFilters) . "\n";

// 5. Time slot generation
function generateTimeSlots(string $start, string $end, int $interval): array {
    $startTime = strtotime($start);
    $endTime = strtotime($end);

    return array_map(function($timestamp) {
        return date('H:i', $timestamp);
    }, range($startTime, $endTime, $interval * 60));
}

echo 'Time slots:' . "\n";
print_r(generateTimeSlots('09:00', '17:00', 30));

These examples demonstrate practical applications of range in web development. From generating test data to creating UI components like pagination controls and time selectors, range provides a concise way to create sequential data structures.

Advanced techniques

Beyond basic sequences, range can be combined with other PHP functions for more advanced use cases. Here are some sophisticated applications.

advanced_techniques.php
<?php

declare(strict_types=1);

// 1. Generating non-linear sequences
function fibonacciRange(int $count): array {
    $sequence = [];
    $a = 0;
    $b = 1;

    foreach (range(1, $count) as $_) {
        $sequence[] = $a;
        [$a, $b] = [$b, $a + $b];
    }

    return $sequence;
}

echo "Fibonacci sequence:\n";
print_r(fibonacciRange(10));

// 2. Creating matrix coordinates
$rows = range(1, 3);
$cols = range('A', 'C');

$matrix = array_map(function($row) use ($cols) {
    return array_map(function($col) use ($row) {
        return $col . $row;
    }, $cols);
}, $rows);

echo "\nMatrix coordinates:\n";
print_r($matrix);

// 3. Weighted random distribution
function weightedRandom(array $weights): int {
    $total = array_sum($weights);
    $random = mt_rand(1, $total);
    $cumulative = 0;

    foreach ($weights as $i => $weight) {
        $cumulative += $weight;
        if ($random <= $cumulative) {
            return $i;
        }
    }

    return array_key_last($weights);
}

$weights = range(1, 5); // Increasing weight
$results = array_fill(0, 5, 0);

foreach (range(1, 10000) as $_) {
    $results[weightedRandom($weights)]++;
}

echo "\nWeighted random distribution:\n";
print_r($results);

// 4. Color gradient generation
function generateGradient(string $start, string $end, int $steps): array {
    $start = hexdec($start);
    $end = hexdec($end);

    return array_map(function($step) use ($start, $end, $steps) {
        $ratio = $step / ($steps - 1);
        $color = $start + ($end - $start) * $ratio;
        return str_pad(dechex((int)$color), 6, '0', STR_PAD_LEFT);
    }, range(0, $steps - 1));
}

echo "\nColor gradient:\n";
print_r(generateGradient('FF0000', '0000FF', 5));

// 5. Calendar generation
function generateCalendar(int $year, int $month): array {
    $firstDay = date('N', strtotime("$year-$month-01"));
    $daysInMonth = date('t', strtotime("$year-$month-01"));

    $weeks = [];
    $day = 1;

    foreach (range(1, 6) as $week) { // Max 6 weeks in a month
        if ($day > $daysInMonth) break;

        $weekDays = [];
        foreach (range(1, 7) as $weekDay) {
            if (($week === 1 && $weekDay < $firstDay) || $day > $daysInMonth) {
                $weekDays[] = null;
            } else {
                $weekDays[] = $day++;
            }
        }

        $weeks[] = $weekDays;
    }

    return $weeks;
}

echo "\nCalendar for May 2025:\n";
print_r(generateCalendar(2025, 5));

These advanced examples demonstrate how range can be part of more complex operations. From generating mathematical sequences to creating color gradients and calendar layouts, range serves as a building block for sophisticated array generation.

Performance considerations

While range is convenient, it's important to understand its performance characteristics, especially when working with large ranges or in performance- critical code.

performance.php
<?php

declare(strict_types=1);

// 1. Memory usage with large ranges
$startMemory = memory_get_usage();
$largeRange = range(1, 1000000);
$endMemory = memory_get_usage();
echo "Memory used for 1,000,000 elements: " .
     ($endMemory - $startMemory) / 1024 / 1024 . " MB\n";

// 2. Generator alternative for large ranges
function xrange($start, $end, $step = 1) {
    for ($i = $start; $i <= $end; $i += $step) {
        yield $i;
    }
}

$startMemory = memory_get_usage();
$xrange = xrange(1, 1000000);
$endMemory = memory_get_usage();
echo "Memory used for generator: " .
     ($endMemory - $startMemory) / 1024 / 1024 . " MB\n";

// 3. Benchmarking range() vs loop
function testRange($count) {

    $start = microtime(true);
    $array = range(1, $count);
    $sum = array_sum($array);
    $time = microtime(true) - $start;
    return "range(): $time seconds\n";
}

function testLoop($count) {

    $start = microtime(true);
    $sum = 0;
    for ($i = 1; $i <= $count; $i++) {
        $sum += $i;
    }
    $time = microtime(true) - $start;
    return "loop: $time seconds\n";
}

$count = 1000000;
echo "\nPerformance comparison for $count elements:\n";
echo testRange($count);
echo testLoop($count);

// 4. Comparing with array_fill
function testRangeFill($count) {
    $start = microtime(true);
    $array = range(0, $count - 1);
    $time = microtime(true) - $start;
    return "range: $time seconds\n";
}

function testArrayFill($count) {
    $start = microtime(true);
    $array = array_fill(0, $count, null);
    $time = microtime(true) - $start;
    return "array_fill: $time seconds\n";
}

echo "\nInitialization comparison for $count elements:\n";
echo testRangeFill($count);
echo testArrayFill($count);

This script demonstrates the memory and performance characteristics of range. For very large ranges, range can consume significant memory, and in some cases, a generator or simple loop may be more efficient. The right choice depends on whether you need all values in memory at once.

λ php performance.php
Memory used for 1,000,000 elements: 18.000076293945 MB
Memory used for generator: 0.000518798828125 MB

Performance comparison for 1000000 elements:
range: 0.010489940643311 seconds
loop: 0.025919198989868 seconds

Initialization comparison for 1000000 elements:
range: 0.0057270526885986 seconds
array_fill: 0.005728006362915 seconds

PHP's range function is a versatile tool for generating sequences of values. Key points to remember:

The range function is particularly valuable when you need to quickly generate arrays of sequential values without writing manual loops. It makes code more readable and expressive while providing good performance for most use cases.

In this article we explored the range function in PHP, its syntax, practical applications, advanced techniques, and performance considerations.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all PHP tutorials.