<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);



/**
 * @author Robert Deiman
 * @copyright 2008
 * @param string $aNumbers This contains the string or  an array with al the numbers u want to use the function on
 * @param string $sSeparator This contains the string that is the separator for the numbers *only used when input $sString is not an array
 * @param boolean $bReturnmissing Set to true, if you also want to see what numbers are missing
 * @param string $sRuleend This is the part that is shown when the last part of the $sString is shown
 */
function createrange($aNumbers,$sSeparator = ' ', $bReturnmissing = false, $sRuleend = '<br />'){
	//check if it is an array if not, create
	if(!is_array($aNumbers)){
		$aNumbers = explode($sSeparator,$aNumbers);
		}

	sort($aNumbers);

	$aNumarray = array();
	$aMissingarray = array();
	for($i=1,$j=1; $i <= max($aNumbers); $i++){
		//for as long numbers keep following eachother up, put them in the standard return array
		if(in_array($i,$aNumbers)){
			$aNumarray[$j][] = $i;		
			}
		//when there's a gap between the numbers, put the missing ones in this other array
		else{
			$aMissingarray[] = $i;
			$j++;
			}
		}
	
	$sReturn = '';
	//Set a separator for between groups of return numbers
	$sShowsep = ', ';
	foreach($aNumarray as $key => $value){
		//when the last key is reached, there will be automatically added a newline. You can change that in the function call
		if($key == end(array_keys($aNumarray))){
			$sShowsep = $sRuleend;
			}
		// for more then 2 numbers show them as 1-4
		if(count($aNumarray[$key]) > 2){
			$sReturn .= min($aNumarray[$key]).'-'.max($aNumarray[$key]).$sShowsep;
			}
		// for exactly 2 numbers show them as 1,2
		elseif(count($aNumarray[$key]) == 2){
			$sReturn .= min($aNumarray[$key]).','.max($aNumarray[$key]).$sShowsep;	
			}
		// for 1 number, just show the number.
		else{
			$sReturn .= min($aNumarray[$key]).$sShowsep;
			}
		}
	//when the option for returning the missing numbers is set: also create a string using this function
	if($bReturnmissing){
		$sReturn .= 'Missing numbers: '.createrange($aMissingarray);
		}
	return $sReturn;
	}
	
//string with space separated
$sSpacesep = '1 2 3 4 6 7 8 10 11 12 13 15 16 20 24 25 26 19';
//string with comma separated
$sCommasep = '1,2,3,5,6,7,12,13,14,16';
//string asked down in the comments on this script
$sPhpstring = '1,2,3,4,6,8,9,10';

// example for how to use it with a space separated string
echo createrange($sSpacesep,' ',true).'<br />';
// example for how to use it with a comma separated string
echo createrange($sCommasep,',');
echo createrange($sPhpstring,',');
?>