3v4l.org

run code in 300+ PHP versions simultaneously
<?php function hyphenate(array $numbers) { $result = []; $ref = null; foreach ($numbers as $i => $number) { if ($ref && $number == $numbers[$i - 1] + 1) { $ref = strtok($ref, "-") . "-$number"; } else { unset($ref); $ref = $number; $result[] =& $ref; } } return implode(',', $result); } var_export([ hyphenate(explode(' ', '')), hyphenate(explode(' ', '1')), hyphenate(explode(' ', '1 2')), hyphenate(explode(' ', '1 3')), hyphenate(explode(' ', '1 3 4 6')), hyphenate(explode(' ', '1 3 4 6 7')), hyphenate(explode(' ', '1 2 3 4 5')), hyphenate(explode(' ', '1 2 3 5 6 10 12 13')), ]);
Output for 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
array ( 0 => '', 1 => '1', 2 => '1-2', 3 => '1,3', 4 => '1,3-4,6', 5 => '1,3-4,6-7', 6 => '1-5', 7 => '1-3,5-6,10,12-13', )

preferences:
57.93 ms | 992 KiB | 4 Q