Gen. partnerAlgotech

Getting the alphabet, arrays of numbers and intervals

``php getNumbers(10, 100);

|
August 22, 2019

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.

Loading comments...

Stay in the loop

Subscribe to our newsletter and get the latest cybersecurity news delivered straight to your inbox.

Your data is safe. You can unsubscribe from the newsletter at any time.