Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a simple way to take a list of numbers which can be in the range 1 - 15. And put a dash in place of consecutive numbers.

So that for example if you had the following numbers:

1 2 3 5 6 7 10 12

It would output

1 - 3, 5 - 7, 10, 12

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
386 views
Welcome To Ask or Share your Answers For Others

1 Answer

<?php
$n = array (1, 2, 3, 5, 6, 7, 10, 12);
sort ($n);   // If necessary.
$i = 0;
while ($i < count ($n))
  {
    if ($i != 0)
      print (", ");
    $rangestart = $i;
    print ($n [$i++]);
    while ($i < count ($n) && $n [$i] == $n [$i - 1] + 1)
      $i++;
    if ($i > $rangestart + 1)
      print (" - " . $n [$i - 1]);
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...