4.3. Initializing an Array to a Range of Integers

Problem

You want to assign a series of consecutive integers to an array.

Solution

Use range($start, $stop) :

$cards = range(1, 52);

Discussion

For increments other than 1, you can use:

function pc_array_range($start, $stop, $step) {
    $array = array();
    for ($i = $start; $i <= $stop; $i += $step) {
        $array[] = $i;
    }
    return $array;
}

So, for odd numbers:

$odd = pc_array_range(1, 52, 2);

And, for even numbers:

$even = pc_array_range(2, 52, 2);

See Also

Recipe 2.5 for how to operate on a series of integers; documentation on range( ) at http://www.php.net/range.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.