php tutorial - How to Create PHP Array Dynamically - php programming - learn php - php code - php script




  • 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.
  • The structure of the range() function is given below
$a = range( lower/upper limit, upper/lower limit, step size );
click below button to copy the code. php tutorial - team

  • 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
click below button to copy the code. php tutorial - team

  • 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
click below button to copy the code. php tutorial - team

  • 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.

Sample Code

<?php 
$a = range(0,100,10); 
echo "Array elements from range() function : ";
foreach($a as $value){
  echo $value." ";
}
?>
click below button to copy the code. php tutorial - team

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.
<?php 
$a = range(50,5,10); 
echo "Array elements from range() function : ";
 foreach($a as $value){ 
  echo $value." ";
 } 
?>
click below button to copy the code. php tutorial - team

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.

Related Searches to How to Create PHP Array Dynamically