Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page