PHP get an array of numbers from string with range [duplicate]
Asked Answered
N

2

8

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
Nitrate answered 17/2, 2016 at 0:14 Comment(0)
W
7

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
)
Warmedover answered 17/2, 2016 at 0:32 Comment(0)
B
3

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);
Begin answered 17/2, 2016 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.