PHP Tutorial - PHP range() Function






Definition

The range() function creates an array of numbers between the first parameter and the second parameter two.

Syntax

PHP range() Function has the following syntax.

range(low,high,step)

Parameter

ParameterIs RequiredDescription
lowRequired.Lowest value of the array
highRequired.Highest value of the array
stepOptional.Increment used in the range. Default is 1.

Note

If the low parameter is higher than the high parameter, the range array will be from high to low.





Return

This function returns an array of elements from low to high.

Example 1

Use range() function to create array

<?PHP
$numbers = range(1,10);
print_r($numbers);
?>

The code above generates the following result.

The third parameter from range() function sets the step. It can either be an integer or a floating-point number.

<?PHP
$numbers = range(1, 10, 2);
print_r($numbers);
print "\n";
$numbers = range(1, 10, 3);
print_r($numbers);
print "\n";
$numbers = range(10, 100, 10);
print_r($numbers);
print "\n";
$numbers = range(1, 10, 1.2);
print_r($numbers);
?>

The code above generates the following result.





Example 2

The third parameter should always be positive.

If the first parameter is higher than the second parameter, we will get an array counting down.

<?PHP
$values = range(100, 0, 10);
print_r($values);

//We can use range() to create arrays of characters:

$values = range("a", "z", 1);
print_r($values);
print "\n";


$values = range("z", "a", 2);
print_r($values);
?>

The code above generates the following result.

Example 3

Create an array containing a range of elements from "0" to "5":

<?php
$number = range(0,5);
print_r ($number);
?>

The code above generates the following result.

Example 4

Return an array of elements from "0" to "50" and increment by 10.

<?php
$number = range(0,50,10);
print_r ($number);
?>

The code above generates the following result.

Example 5

Using letters - return an array of elements from "a" to "d"

<?php
$letter = range("a","d");
print_r ($letter);
?>

The code above generates the following result.