Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get an array of numbers from string with range

For my current project I need an user to define a range of numbers which is stored in a database.

The following string is a possible user input:

1025-1027,1030,1032-1034

I want to process this string with php to get an array of possible numbers including the possibility to add a range of numbers with n-n² or adding single numbers separated with n; n² which for this example would be:

1025 1026 1027 1030 1032 1031 1034
like image 828
Stanley Machnitzki Avatar asked Feb 17 '16 00:02

Stanley Machnitzki


People also ask

Can we echo array in PHP?

How do I echo an array in PHP? Use foreach Loop to Echo or Print an Array in PHP. Use print_r() Function to Echo or Print an Array in PHP. Use var_dump() Function to Echo or Print an Array in PHP.

What does In_array return in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


2 Answers

Split the input string by comma and then see what each element of the new array is. If it has the range delimiter (-), add each number from the range to the array:

$input = '1025-1027,1030,1032-1034';

$inputArray = explode(',', $input);
$outputArray = array();

foreach($inputArray as $v) {
    if(strpos($v, '-') === false) {
        $outputArray[] = $v;
    } else {
        $minMax = explode('-',$v);

        if($minMax[0]<=$minMax[1]) {
            $outputArray = array_merge($outputArray, range($minMax[0], $minMax[1]));
        }
    }
}

print_r($outputArray);

The value returned in the end is

Array
(
    [0] => 1025
    [1] => 1026
    [2] => 1027
    [3] => 1030
    [4] => 1032
    [5] => 1033
    [6] => 1034
)
like image 132
Alex Karshin Avatar answered Sep 24 '22 10:09

Alex Karshin


Another way / variant would be to explode both , and -, then map each exploded group then use range, after the ranges has been created, remerge the grouping:

$input = '1025-1027,1030,1032-1034';
// explode, map, explode, create range
$numbers = array_map(function($e){
    $range = explode('-', $e);
    return (count($range) > 1) ? range(min($range), max($range)) : $range;
}, explode(',', $input));
// re merge
$numbers = call_user_func_array('array_merge', $numbers);
print_r($numbers);
like image 21
Kevin Avatar answered Sep 25 '22 10:09

Kevin