Blog /Ahmad Is A Rockstar

January 23, 2007 22:39 +0000  |  Programming Riptown 0

One of my coworkers helped me out of a jam by writing some amazing math-foo the other day and I wanted to share:

public static function getDefinitionFromSerials($in) {

	$out = array();
	if ($in) {

		sort($in);

		$n = $in[0];
		for ($i = 1; $i < count($in); $i++) {
			$z = $n;
			if ($in[$i] != $in[$i-1] + 1) {
				if ($z == $in[$i-1]) {
					$out[] = $z;
				} elseif ($z + 1 == $in[$i-1]) {
					$out[] = $z;
					$out[] = $in[$i-1];
				} else {
					$out[] = $z .'-'. $in[$i-1];
				}
				$n = $in[$i];
			}
		}
		if (count($in) == 1 || $z != $n) {
			$out[] = $n;
		} elseif ($z+1 == $in[count($in)-1]) {
			$out[] = $n;
			$out[] = $in[count($in)-1];
		} else {
			$out[] = $z .'-'. $in[count($in)-1];
		}

	}

	return implode(',', $out);

}

The above is an algorithm that transforms an array of numbers (1,2,3,7,9,10,11) into a human readable range or fieldset such as "1-3,7,9-11". I spent hours online googling for the solution and found nothing so I thought I'd share it here in the hopes that someone else might find it useful.

Comments

Post a Comment of Your Own

Markdown will work here, if you're into that sort of thing.