Skip to content

Core\Arr::range

Core\Arr::range(int $start, int $end, {step?: int}): array<int>Core\Arr::range(
    int $start,
    int $end,
    {step?: int},
): array<int>

Returns a list of the whole numbers between two bounds. Both bounds are part of the list.

You give the first number and the last number. The list counts up when the first number is smaller, and it counts down when the first number is larger. When both are the same, the list holds that one number. The step option sets the distance between neighbours, and it is 1 by default. A step is always a positive number, because the direction comes from the two bounds. A step that would pass the last number stops at the last number inside the bounds. A step of 0 or less throws a RuntimeError.

The examples below show a plain count, a count down and a count in steps of two, and the page numbers under a list of search results.

Parameters

  • $startintThe first value.
  • $endintThe last value that may appear. When a step goes past it, the list stops at the last value inside the range.

Options

  • stepintoptionalThe distance between two neighbouring values, 1 by default. It is always positive, because $start and $end set the direction.

Return value

Returns array<int>. A list from $start towards $end; one entry when the two are equal.

Errors

  • RuntimeErrorstep is 0 or negative.

Examples

Count from one to five

<?nvs
// Shows how to build a list of the whole numbers between two bounds.
// The numbers 1 to 5. Both bounds are part of the list.
array<int> $numbers = Core\Arr::range(1, 5);
// This prints 5.
echo Core\Arr::count($numbers), "\n";
// This prints the numbers 1 to 5, each on its own line.
foreach ($numbers as int $number) {
echo $number, "\n";
}
Output
5
1
2
3
4
5

Count down and count in steps

<?nvs
// Shows the two things that change the numbers you get: the order of the
// bounds, and the `step` option.
// The first number is larger than the last, so this counts down. It prints
// 3, 2 and 1.
array<int> $countdown = Core\Arr::range(3, 1);
foreach ($countdown as int $number) {
echo $number, "\n";
}
// A step of 2 puts a distance of 2 between neighbours. This prints 1, 3, 5, 7
// and 9. A step of 2 from 9 passes 10, so the list stops at 9.
array<int> $odd = Core\Arr::range(1, 10, { step: 2 });
foreach ($odd as int $number) {
echo $number, "\n";
}
Output
3
2
1
1
3
5
7
9

The page numbers of a result list

<?nvs
// Shows how to build the page links under a list of search results. This
// search filled 5 pages, and the reader is on page 3.
int $pages = 5;
int $current = 3;
// One line per page. The page the reader is on is printed without a link.
foreach (Core\Arr::range(1, $pages) as int $page) {
if ($page == $current) {
echo $page, "\n";
} else {
echo '<a href="?page=', $page, '">', $page, '</a>', "\n";
}
}
Output
<a href="?page=1">1</a>
<a href="?page=2">2</a>
3
<a href="?page=4">4</a>
<a href="?page=5">5</a>