Calendar CODE

// Example usage:
$year = 2023;
$month = 1; // May

function generateMonthArray($year, $month) {
    $numDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $firstDay = date("N", strtotime("$year-$month-01")); // 1 = Monday, 7 = Sunday

    $weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

    $monthArray = array_fill_keys($weekdays, []);

    for ($day = 1; $day <= $numDays; $day++) {
        $weekday = ($firstDay + $day - 2) % 7; // Adjust to start from Monday
        $monthArray[$weekdays[$weekday]][] = $day;
    }
    
    foreach ($monthArray as &$weekDays) {
    	if ($weekDays[0]!=1) {
    		array_unshift($weekDays, '');
    	} else {
    		break;
    	}
    }

    return $monthArray;
}

$result = generateMonthArray($year, $month);

// Print the result
foreach ($result as $weekday => $days) {
    echo $weekday . "\t" . implode("\t", $days) . "\n";
}
by Valeri Tandilashvili
1 year ago
PHP
0
Pro tip: use ```triple backticks around text``` to write in code fences