Skip to content
PHP Logo

How can PHP be used to generate an array of dates representing a full week based on a given date, taking into account different start-of-week settings?

To generate an array of dates representing a full week based on a given date, we need to consider the start-of-week setting to ensure consistency. One approach is to calculate the start and end dates of the week based on the given date and the start-of-week setting. We can then loop through the days of the week and generate an array of dates accordingly.

php
function generateWeekDates($givenDate, $startOfWeek) {
    $start = new DateTime($givenDate);
    $start->modify('this '.$startOfWeek);
    
    $dates = array();
    for ($i = 0; $i < 7; $i++) {
        $dates[] = $start->format('Y-m-d');
        $start->modify('+1 day');
    }
    
    return $dates;
}

$givenDate = '2022-01-15';
$startOfWeek = 'Monday';
$weekDates = generateWeekDates($givenDate, $startOfWeek);

print_r($weekDates);