Creating an array of numbers

array range ( int low, int high [, int step])

Consider this problem:

  • A school has to give all its students an end-of-year examination

  • The test consists of the same 40 questions for each student

  • To minimise cheating, the school wants those 40 questions to be randomly ordered

How would you code that in PHP? The obvious answer is code like this:

<?php
    $questions = array(1, 2, 3, 4, 5, ..., 38, 39, 40);
    $questions = shuffle($questions);
?>

The slightly smarter programmer might save themselves some typing with more intelligent code like this:

<?php
    for ($i = 1; $i <= 40; ++$i) {
        $questions[] = $i;
    }
    
    shuffle($questions);
?>

However, that's still not the most efficient way of doing it. Instead, PHP has a special range() function that allows you to create an array of numbers between a low value (parameter one) and a high value (parameter two). So the best way to write the script is this:

<?php
    $questions = range(1,40);
    $questions = shuffle($questions);
?>

As you can see, range() returns the array between 1 and 40 (inclusive), ordered sequentially. This is then passed through shuffle() to get the random question numbers - perfect!

There are a three other tricks to range() that you should be aware of. Firstly, it has a third parameter that allows you specify a step amount in the range. 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);

Although the step parameter should always be positive, the second trick is that 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);

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);

For creating these simple kinds of arrays, there is nothing better than using range() - it is very fast, very easy to read, and the step parameter can save you extra work.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Multidimensional arrays >>

Previous chapter: Randomising your array

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.