How can the PHP code be optimized to efficiently group and display course listings by day?

To efficiently group and display course listings by day in PHP, we can use an associative array where the keys are the days of the week and the values are arrays of course listings for that day. We can then loop through the course listings and add them to the corresponding day in the associative array. Finally, we can loop through the associative array to display the course listings grouped by day.

// Sample course listings
$courseListings = [
    ['title' => 'Course A', 'day' => 'Monday'],
    ['title' => 'Course B', 'day' => 'Tuesday'],
    ['title' => 'Course C', 'day' => 'Monday'],
    ['title' => 'Course D', 'day' => 'Wednesday'],
];

// Group course listings by day
$groupedCourses = [];
foreach ($courseListings as $course) {
    $day = $course['day'];
    $groupedCourses[$day][] = $course;
}

// Display course listings grouped by day
foreach ($groupedCourses as $day => $courses) {
    echo "<h2>{$day}</h2>";
    foreach ($courses as $course) {
        echo "<p>{$course['title']}</p>";
    }
}