I'm trying to work out the page range of numbers that exist in an array. I did attempt to search google for it but I only found unrelated posts/pages.
The code I have been working on is:
$numbers = array(1,3,2,4,5,6,7,8,9,11,10,15,14,13,12,16,17,18,19,20,22);
function get_number_ranges($numbers)
{
$last = null;
foreach ($numbers as $number) {
if (is_null($last)) {
$string = $number;
$last = $number;
} elseif ($last + 1 != $number) {
$string .= '-' . $last . ', ' . $number;
$last = $number;
} else {
$last = $number;
}
}
if ($last == $number) {
$string .= '-' . $number;
}
return $string;
}
and that produces
1-1, 3-3, 2-2, 4-9, 11-11, 10-10, 15-15, 14-14, 13-13, 12-12, 16-20, 22-22
I don't want it to display the duplicate number, so i want it to look like this:
1, 3, 2, 4-9, 11, 10, 15, 14, 13, 12, 16-20, 22
This is so i can represent page ranges when storing history about a document.
Im sure this will be a nice easy one for some1, any help will be greatly received!