3v4l.org

run code in 300+ PHP versions simultaneously
<?php function splitAndMergeDateRanges(array $dateRanges): array { if (empty($dateRanges)) { return []; } // First, sort the date ranges by their start date usort($dateRanges, function($a, $b) { return strcmp($a['start'], $b['start']); }); $mergedRanges = []; $currentRange = $dateRanges[0]; foreach ($dateRanges as $range) { if ($range['start'] <= $currentRange['end']) { // If the current range overlaps with the new range, merge them $currentRange['end'] = max($currentRange['end'], $range['end']); } else { // If they don't overlap, add the current range to the merged list $mergedRanges[] = $currentRange; // and start a new range $currentRange = $range; } } // Don't forget to add the last range $mergedRanges[] = $currentRange; return $mergedRanges; } // Example input $dateRanges = [ ["start" => "2024/06/11", "end" => "2024/06/12"], ["start" => "2024/06/12", "end" => "2024/06/13"], ["start" => "2024/06/13", "end" => "2024/06/14"], ["start" => "2024/06/14", "end" => "2024/06/15"], ["start" => "2024/06/15", "end" => "2024/06/16"], ["start" => "2024/06/16", "end" => "2024/06/17"], ["start" => "2024/06/17", "end" => "2024/06/18"], ["start" => "2024/06/18", "end" => "2024/06/19"], ["start" => "2024/06/19", "end" => "2024/06/20"], ["start" => "2024/06/20", "end" => "2024/06/21"], ["start" => "2024/06/22", "end" => "2024/06/23"], ["start" => "2024/06/23", "end" => "2024/06/24"], ["start" => "2024/06/24", "end" => "2024/06/25"], ["start" => "2024/06/25", "end" => "2024/06/26"], ["start" => "2024/06/26", "end" => "2024/06/27"], ["start" => "2024/06/27", "end" => "2024/06/28"], ["start" => "2024/06/28", "end" => "2024/06/29"], ["start" => "2024/06/29", "end" => "2024/06/30"] ]; print_r(splitAndMergeDateRanges($dateRanges)); splitAndMergeDateRanges($dateRanges);
Output for 8.1.0 - 8.1.29, 8.2.0 - 8.2.20, 8.3.0 - 8.3.8
Array ( [0] => Array ( [start] => 2024/06/11 [end] => 2024/06/21 ) [1] => Array ( [start] => 2024/06/22 [end] => 2024/06/30 ) )

preferences:
64.85 ms | 403 KiB | 65 Q