Location: PHPKode > scripts > Number Sequence > number-sequence/numberSequence.class.php
<?php
/**
 * Class method 'format' expects an array with numbers (array(1,2,3,5,7,8,9)) 
 * and returns a string with the sequence (1-3, 5, 7-9)
 * 
 * class numberSequence, 30-05-2007
 * author: Ronald Klaassen (hide@address.com)
 * 
 * No need to instantiate the class, just use numberSequence::format($array)
 *
 */
class numberSequence
{
	/**
	 * Format your number sequence
	 *
	 * @param array $array
	 * @return string
	 */
	public function format($array)
	{
		$separator = ', ';
		$combinator = ' - ';
		if (is_array($array))
		{
			// test if array contains numbers
			$continue = true;
			foreach ($array as $number)
			{
				if (!is_numeric($number))
				{
					$continue = false;
				}
			}
			if ($continue)
			{              
                // remove double values
                $array = numberSequence::removeDoubleValues($array);
                 
				// sort array
				sort($array, SORT_NUMERIC);
				
				$startnumber = false;
				$array_string = "";
				for ($i=0;$i<count($array);$i++)
				{
					$number = $array[$i];
					if ($i != (count($array)-1))
					{
						$nextnumber = $array[($i+1)];
						if ($nextnumber == ($number+1))
						{
							if ($startnumber === false)
							{
								$startnumber = $number;
							}
						}
						else 
						{
							if ($startnumber !== false)
							{
								if ($startnumber != $array[0])
								{
									$array_string .= $separator;
								}
								$array_string .= "$startnumber$combinator$number";
								$startnumber = false;
							}
							else
							{
								if ($i != 0)
								{
									$array_string .= $separator;
								}
								$array_string .= $number;
							}
						}
					}
					else 
					{	
						if ($startnumber !== false)
						{
							if ($startnumber != $array[0])
							{
								$array_string .= $separator;
							}
							$array_string .= "$startnumber$combinator$number";
						}
						else
						{
							if ($i != 0)
							{
								$array_string .= $separator;
							}
							$array_string .= $number;
						}
					}
				}
				return $array_string;
			}
			else { return "Array contains other values dan integers"; }
		}
		else { return "No array given"; }
	}  
    
    /**
    * Removes double values from array
    * 
    * @param array $array
    * @return array $returnArray 
    */
    private function removeDoubleValues($array) 
    {
        $returnArray = array();
        foreach ($array as $number)
        {
            if (!in_array($number, $returnArray))
            {
                $returnArray[] = $number;
            }
        }
        return $returnArray;
    } 
}
?>
Return current item: Number Sequence