PHP Manual
/

Getting the alphabet, arrays of numbers and intervals

2019-08-22T18:48:46.000Z

Quite often we need to have an array of values that are derived by a very simple algorithm (for example an array of numbers from $min to $max), this can be solved either in a complicated way:

``php
getNumbers(10, 100);

/**

  • @return int[]
    */
    function getNumbers(int $min, int $max): array
    {
    $numbers = [];
    for ($i = $min; $i <= $max; $i++) {
    $numbers[] = $i;
    }

return $numbers;
}

Or use the ready-made function `range($min, $max, $step)`:

php
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
foreach (range(0, 12) as $number) {
echo $number . '; ';
}

// [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
foreach (range(0, 100, 10) as $number) {
echo $number . '; ';
}

// ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
foreach (range('a', 'i') as $char) {
echo $char . '; ';
}

// ['c', 'b', 'a']
foreach (range('c', 'a') as $char) {
echo $char . '; ';
}
```

This function has use in the Paginator module, for example, which handles pagination of a long list of results, or general sorting into a catalog.

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

1.
2.
Status:
All systems normal.
2025