How to Create PHP Array Dynamically

PHP provides some built-in array functions which help to do array operation so easily. The range() function is one of them. With the range() function, PHP numeric array can be created dynamically. This article will show how to create PHP numeric array dynamically with the range() function.

Dynamic Array with range() Function in PHP

Dynamic Array with range() Function in PHP

The structure of the range() function is given below…

$a = range( lower/upper limit, upper/lower limit, step size );

Here, the array variable $a will be numeric array whose elements start from lower limit and end at upper limit. Step size determines the number of array elements. So, if the lower limit is 0 and the upper limit is 100 and the step size is 10, the array elements will be calculated from the below mathematics…

{(upper limit – lower limit)/step size}+1 = {(100 – 0)/10}+1 =  11

Again, if the lower limit is 5 and the upper limit is 50 and the step size is 10, the elements will be…

{(upper limit – lower limit)/step size}+1 = {(50 – 5)/10}+1 = 5.5

Here, the result is a fraction number. In this case, PHP will ignore the fraction value and take the lower round figure. So, the array elements will be 5.

See below example…


<?php 
$a = range(0,100,10); 
echo "Array elements from range() function : ";
foreach($a as $value){
  echo $value." ";
}
?>

Output

Array elements from range() function : 0 10 20 30 40 50 60 70 80 90 100

The example is showing that the array $a has been created dynamically with the range() function and the elements are being increased from lower limit to upper limit. But the range() function can also create an array whose elements will be decreased from upper limit to lower limit. See below example…


<?php 
$a = range(50,5,10); 
echo "Array elements from range() function : ";
 foreach($a as $value){ 
  echo $value." ";
 } 
?>

Output

Array elements from range() function : 50 40 30 20 10

Here, the array elements are starting from upper limit and end with lower limit. So, with the range() function both types of array can be created.

Creating numeric array dynamically with the range() function has been explained in this article. If you face any problem to understand this article, feel free to contact with me from Contact us page. I’ll try my best to stay with you. Adding array elements with PHP array function will be explained in next article. Spend some time to study the article and learn how to add PHP array elements with PHP array function.

2 Comments
  1. True Religion Outlet
  2. Sayeed

Leave a Reply to True Religion Outlet Cancel reply

Your email address will not be published. Required fields are marked *