Function – convert list of numbers (comma separated) to range (compress)

Standard

Example: 1, 3, 4, 5, 6 to 1,3-6

Implementation using PHP (For other language, you just need to modify some part of it)

function commaToRange($commaString)
{
	$rangeString = "";
	
	$arr = explode (",", $commaString);
	// to remove space
	$commaString = str_replace(" ", "", $commaString);

        // as the scope is integer, step is set to 1
	$step = 1;
		
	// if there are at least 2 numbers
	if (count($arr)> 1) 
	{
		$start = 0;
			
		for ($i = 1; $i < count($arr); $i++)
		{
			// if current range ends (=discontinued), print the last value of the range and print ',' to indicate start of new range 
			if ($arr[$i] - $arr[$i-1] > $step)
			{
				$rangeString .= $arr[$i-1];
				$rangeString .= ",";
				$start = $i;
			}
			// if current range keeps continuous, do nothing. (if the range keep continuous until second number, print the first value of the range and '-' to indicate range)
			else
			{
				if ($i - 1 == $start)
					$rangeString .= $arr[$i-1]."-";
			}
				
			// if the element is last, force printing
			if (count($arr) -1 == $i)
					$rangeString .= $arr[$i];
			}
	}
	// if there are only one number or less, return input itself
	else 
		$rangeString = $commaString;
		
	return $rangeString;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.