I’m working on an array of numeric values.
I have a array of numeric values as the following in PHP
11,12,15,16,17,18,22,23,24
And
I have used this one before, it does the trick.
Takes as input a comma separated string of numbers. Call to sort
could be ignored if numbers are guaranteed to be sorted already.
function range_string($csv)
{
// split string using the , character
$number_array = array_map('intval', explode(',', $csv));
sort($number_array);
// Loop through array and build range string
$previous_number = intval(array_shift($number_array));
$range = false;
$range_string = "" . $previous_number;
foreach ($number_array as $number) {
$number = intval($number);
if ($number == $previous_number + 1) {
$range = true;
}
else {
if ($range) {
$range_string .= "-$previous_number";
$range = false;
}
$range_string .= ",$number";
}
$previous_number = $number;
}
if ($range) {
$range_string .= "-$previous_number";
}
return $range_string;
}
$csv_string = "11,16,12,17,18,15,22,23,24";
print range_string($csv_string); // 11-12,15-18,22-24