3v4l.org

run code in 300+ PHP versions simultaneously
<?php $properties_no = ['1021-5150', '1021-5152', '1021-5153', '1021-5154', '1021-5156', '1021-5157', '1021-5158', '1021-5159', '1021-5161', '1021-5162', '1021-5163']; final class Range { private string $from; private string $to; public function __construct(string $from, string $to) { $this->from = $from; $this->to = $to; } public function __toString(): string { return $this->from === $this->to ? $this->from : "{$this->from} to {$this->to}"; } } /** * @param string[] $values * @return Range[] */ function computeRanges(array $values): array { if (count($values) === 0) { return []; } $ranges = []; $first = $previous = $values[0]; $previousIntValue = (int)str_replace('-', '', $first); foreach (array_slice($values, 1) as $value) { $intValue = (int)str_replace('-', '', $value); if ($intValue > $previousIntValue + 1) { $ranges[] = new Range($first, $previous); $first = $value; } $previous = $value; $previousIntValue = $intValue; } $ranges[] = new Range($first, $previous); return $ranges; } echo implode(PHP_EOL, computeRanges($properties_no));
Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 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
1021-5150 1021-5152 to 1021-5154 1021-5156 to 1021-5159 1021-5161 to 1021-5163
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33
Parse error: syntax error, unexpected 'string' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /in/7EPCd on line 7
Process exited with code 255.

preferences:
105.5 ms | 1510 KiB | 4 Q