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
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.
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.
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
)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With