Name

range()

Synopsis

    array range ( mixed low, mixed high [, number step] )

The range() function creates an array of numbers between a low value (parameter one) and a high value (parameter two). So, to get an array of the sequential numbers between 1 and 40 (inclusive), you could use this:

    $numbers = range(1,40);

The range() function has a third parameter that allows you specify a step amount in the range. This can either be an integer or a floating-point number. For example:

    $questions = range(1, 10, 2);
    // gives 1, 3, 5, 7, 9

    $questions = range(1, 10, 3)
    // gives 1, 4, 7, 10

    $questions = range(10, 100, 10);
    // gives 10, 20, 30, 40, 50, 60, 70, 80, 90, 100

    $float = range(1, 10, 1.2);
    // gives 1, 2.2, 3.4, 4.6, 5.8, 7, 8.2, 9.4

Although the step parameter should always be positive, if your low parameter (parameter one) is higher than your high parameter (parameter two), you get an array counting down, like this:

    $questions = range(100, 0, 10);
    // gives 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0

Finally, you can also use range() to create arrays of characters, like this:

    $questions = range("a", "z", 1);
    // gives a, b, c, d, ..., x, y, z

    $questions = range("z", "a", 2);
    // gives z, x, v, t, ..., f, d, b

Get PHP in a Nutshell 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.