3v4l.org

run code in 300+ PHP versions simultaneously
<?php $open_hours = array ( "Sun" => "11am-12am", "Mon" => "11am-12am", "Tue" => "11am-12am", "Wed" => "10am-12am", "Thu" => "9am-12am", "Fri" => "11am-12am", "Sat" => "11am-12am" ); $result = []; $previous = false; foreach ($open_hours as $day => $hours) { if (!$previous || $previous !== $hours) { $result[$hours][] = $day; } elseif ($previous === $hours) { $key = array_key_last($result[$hours]); $current = strtok($result[$hours][$key], '-'); $result[$hours][$key] = $current.'-'.$day; } $previous = $hours; } // build output (joining days with ,) $output = []; foreach ($result as $hours => $days) { $output[] = implode(', ', $days).': '.$hours; } // join with ;'s and output echo implode('; ', $output);
Output for 7.3.0 - 7.3.33, 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
Sun-Tue, Fri-Sat: 11am-12am; Wed: 10am-12am; Thu: 9am-12am
Output for 7.2.0 - 7.2.34
Fatal error: Uncaught Error: Call to undefined function array_key_last() in /in/tKOlI:18 Stack trace: #0 {main} thrown in /in/tKOlI on line 18
Process exited with code 255.
Output for 5.6.0
Fatal error: Call to undefined function array_key_last() in /in/tKOlI on line 18
Process exited with code 255.

preferences:
100.77 ms | 1533 KiB | 4 Q