ZetCode

PHP range 函数

最后修改于 2025 年 5 月 21 日

在本文中,我们将探讨 PHP 的 range 函数,这是一种创建包含一系列元素的数组的便捷方法。 range 函数生成一个包含起始值和结束值之间元素的数组,并可选择元素之间的步长。

当您需要快速生成数字或字符序列而无需编写手动循环时,range 函数特别有用。它通常用于创建测试数据、初始化数组以及生成用于迭代的序列。

PHP 的 range 函数的优点是

通过使用 range,开发人员在处理 PHP 中的一系列值时可以编写更简洁、更具表现力的代码。

基本 range 语法

range 函数接受两个必需参数(开始和结束)和一个可选参数(步长)。

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

开始参数是包含的,而结束参数是排除的。 步长参数定义生成数组中元素之间的增量。 语法如下

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

这演示了 range 与不同类型值的基本用法。 该函数处理升序和降序范围,并适用于整数、浮点数和字符序列。 步长参数控制值之间的增量。

实际用例

range 函数在 PHP 开发中有很多实际应用。 以下是它特别有用的常见场景。

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

这些示例演示了 range 在 Web 开发中的实际应用。 从生成测试数据到创建分页控件和时间选择器等 UI 组件,range 提供了一种创建顺序数据结构的简洁方法。

高级技术

除了基本序列之外,range 还可以与其他 PHP 函数结合使用,以用于更高级的用例。 以下是一些复杂的应用。

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

这些高级示例演示了 range 如何成为更复杂操作的一部分。 从生成数学序列到创建颜色渐变和日历布局,range 充当用于复杂数组生成的构建块。

性能注意事项

虽然 range 很方便,但了解其性能特征很重要,尤其是在处理大范围或性能关键代码时。

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

此脚本演示了 range 的内存和性能特征。 对于非常大的范围,range 可能会消耗大量内存,在某些情况下,生成器或简单循环可能更有效。正确的选择取决于您是否需要一次将所有值都保存在内存中。

λ 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 的 range 函数是一个用于生成一系列值的多功能工具。 要记住的要点

当您需要快速生成顺序值的数组而无需编写手动循环时,range 函数特别有价值。 它使代码更具可读性和表现力,同时为大多数用例提供了良好的性能。

在本文中,我们探讨了 PHP 中的 range 函数、其语法、实际应用、高级技术和性能考虑因素。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 教程