generate an array with a range using PHP

0
127
How to generate an array of strings numbers with a specific range

Welcome back to shorltearner.com, we are starting a new series of PHP interview questions for beginners and experienced,so in previous post we learn, Converting words to numbers in PHP
In this post we see how to generate an array with a range taken from a string.

How to generate an array of strings numbers with a specific range

Also Read
Unable to create a directory a wordpress error
PHP program that multiplies corresponding elements of two given lists
PHP program to print out the multiplication table up to 6*6
Write a PHP program to check if the bits of the two given positions of a number are same or not

 <?php
function string_range($str1) 
{
  preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $str1, $a);
  $x = array ();
  foreach ($a[1] as $k => $v) 
  {
    $x  = array_merge ($x, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
  }
  return ($x);
}
$test_string = '1-2 18-20 9-14';
print_r(string_range($test_string));
?> 

Output

Array ( [0] => 1 [1] => 2 [2] => 18 [3] => 19 [4] => 20 [5] => 9 [6] => 8 [7] => 7 [8] => 6 [9] => 5 [10] => 4 )

another way to find range between to given numbers with the help of php predefined function range(), see the below example

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

Output

Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 )