PHP range() Function with examples

In this tutorial, we will learn about the range() function in PHP. We will see the functionality of the range function in PHP through an example. Hope you like this tutorial. Do share with your friends.

Range Function in PHP

The range() function in PHP is used for creating an array of elements in a particular range. It is used for creating an array containing a particular range of elements.

Let’s see more in detail about the range() function.

Syntax:

range(dataType $startVal, dataType $endVal, int/float $step:1)

So, it will return an array that contains elements starting from the lower value which is the start value and go to the end value which is the end value. In this process either we will increment or decrement the value with the help of step.

So, the range() function finally returns an array of inclusive start and end values.

Code example:

<?php
$number_list_array = range(10,20);
print_r ($number_list_array);
echo "<br /> ";
$number_list_array_step = range(2,20,2);
print_r ($number_list_array_step);
echo "<br /> ";
$letter_list_array = range("s","z");
print_r ($letter_list_array);
?>
OUTPUT:
Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 13 [4] => 14 [5] => 15 [6] => 16 [7] => 17 [8] => 18 [9] => 19 [10] => 20 )
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 [5] => 12 [6] => 14 [7] => 16 [8] => 18 [9] => 20 )
Array ( [0] => s [1] => t [2] => u [3] => v [4] => w [5] => x [6] => y [7] => z )

From the above example, we can see that we used range() function with or without step.

Hope you liked this tutorial. Keep learning!!
Also Read : PHP array_key_exists() Function

 

Leave a Reply

Your email address will not be published.