November 13, 2010 in PHP, Tutorials by admin

Many people work far too hard and write too many lines code to achieve what PHP has already built in. If you have ever created an array of numbers or letters trying to get a range of numbers like from 1-10, 10-100 in intervals of 10, or even a range of letters from A to Z then you will most definitely find range() extremely helpful.

You can easily create a series of sequential numbers and alphabetical letters with range() and with very little code. When I had originally heard about the range function I immediately recognized the many applications of something so simple. With range() in php you can easily create dynamic pagination with both individual pages and incremental stepped pagination. Same thing goes with displaying search results, gallery photos, e-commerce products, or even a simple counter. With the alphabetical range you can easily create directories sorted by individual letters, show a certain range of viewable letters, etc. This is perfect for administrative systems that use names or directories that use names.

So how do we use the range function? Let’s start with something very simple. We will count from 1 to 10 using a foreach loop and the range() function.

1
2
3
4
5
6
7
8
9
10
11
<?php
    // array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    foreach (range(1, 10) as $number) {
        echo $number." ";
    }
?>

This code will output:

0 1 2 3 4 5 6 7 8 9 10

As of PHP 5.0 a step parameter was added to range(). Currently the range function has 3 parameters. The first parameter is your starting number or letter, the second parameter is your ending number or letter, and the third parameter defines at what interval (step) to display the results.

Here is an example of the step parameter and range() where we will count from 50 to 100 in intervals of 5

1
2
3
4
5
6
7
8
9
10
11
<?php
    // array(50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 )

    foreach (range(50, 100, 5) as $number) {
        echo $number." ";
    }
?>

This code will output:

50 55 60 65 70 75 80 85 90 95 100

The same concept applies to letters. Here is an example of using range() with letters. You can go both forward and backward with range() making ascending and descending results a piece of cake.

1
2
3
4
5
6
7
8
9
10
11
<?php
    // array('a', 'b', 'c', 'd', 'e', 'f', 'g',...);

    foreach (range('a', 'z') as $letter) {
        echo $letter. " ";
    }
?>

This code will output:

a b c d e f g h i j k l m n o p q r s t u v w x y z

Here is an example of a descending range of letters displaying every other letter.

1
2
3
4
5
6
7
8
9
10
11
<?php
    // array('z', 'x', 'v', 't', 'r', 'p', 'n',... );

    foreach (range('z', 'a', 2) as $letter) {
        echo $letter." ";
    }
?>

This code will output:

z x v t r p n l j h f d b

So next time you need to create a range of letters or numbers you’ll never have to worry about needing to manually create an array with the range.