PHP range() Function
In this chapter you will learn:
- Definition for PHP range() Function
- Syntax for PHP range() Function
- Parameter for PHP range() Function
- Note for PHP range() Function
- Return value for PHP range() Function
- Example - Use range() function to create array
- Example - Letter range
- Example - Create an array containing a range of elements from "0" to "5"
- Example - Return an array of elements from "0" to "50" and increment by 10
- Example - Using letters - return an array of elements from "a" to "d"
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
Parameter | Is Required | Description |
---|---|---|
low | Required. | Lowest value of the array |
high | Required. | Highest value of the array |
step | Optional. | 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/*from jav a 2 s . c om*/
$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/*from j a v a 2s . com*/
$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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP reset() Function
- Syntax for PHP reset() Function
- Parameter for PHP reset() Function
- Return from PHP reset() Function
- Related methods for PHP reset() Function
- Example - Using current and next and reset
- Example - A demonstration of all related methods