How can the for loop in the PHP function be optimized to prevent the output of duplicate dates?
The issue of duplicate dates being output in the for loop can be solved by using an associative array to store the dates as keys. Before outputting a date, we can check if it already exists in the array and skip it if it does. This way, we can ensure that only unique dates are displayed in the output.
function displayUniqueDates($dates) {
$uniqueDates = array();
foreach ($dates as $date) {
if (!isset($uniqueDates[$date])) {
echo $date . "<br>";
$uniqueDates[$date] = true;
}
}
}
// Example usage
$dates = ["2022-01-01", "2022-01-02", "2022-01-01", "2022-01-03", "2022-01-02"];
displayUniqueDates($dates);