Skip to content

Instantly share code, notes, and snippets.

@DracoBlue
Created February 23, 2011 20:22
Show Gist options
  • Save DracoBlue/841110 to your computer and use it in GitHub Desktop.
Save DracoBlue/841110 to your computer and use it in GitHub Desktop.
<?php
/**
* Reconstruct an array, for small task at: http://www.phpgangsta.de/kleine-aufgabe-ein-array-umbauen
* Contribution by DracoBlue
*/
function compress($in)
{
$in_length = count($in);
$start = $last = $current = $in[0];
$direction = 0;
$out = array();
$i = 1;
while ($i < $in_length)
{
$last = $current;
$current = $in[$i++];
if ($last - 1 === $current && $direction >= 0)
{
$direction = 1;
continue;
}
elseif ($last + 1 === $current && $direction <= 0)
{
$direction = -1;
continue;
}
elseif ($start !== $last)
{
$out[] = $start . '-' . $last;
}
else
{
$out[] = $start;
}
$direction = 0;
$start = $current;
}
$last = $current;
if ($start !== $last)
{
$out[] = $start . '-' . $last;
}
else
{
$out[] = $start;
}
return $out;
}
function decompress($in)
{
$out = array();
foreach ($in as $current)
{
if (is_string($current))
{
list($start, $end) = explode('-', $current);
foreach (range($start, $end) as $value)
{
$out[] = $value;
}
}
else
{
$out[] = $current;
}
}
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment