How can PHP be used to calculate the number of working days between two dates, excluding weekends and holidays?

To calculate the number of working days between two dates in PHP, excluding weekends and holidays, you can use a loop to iterate through each day between the two dates. Within the loop, you can check if the current day is a weekend (Saturday or Sunday) or a holiday, and exclude it from the count if it is. Finally, you can return the total number of working days calculated.

function getWorkingDays($startDate, $endDate, $holidays) {
    $workingDays = 0;
    
    $currentDate = strtotime($startDate);
    $end = strtotime($endDate);
    
    while ($currentDate <= $end) {
        $dayOfWeek = date('N', $currentDate);
        
        if ($dayOfWeek < 6 && !in_array(date('Y-m-d', $currentDate), $holidays)) {
            $workingDays++;
        }
        
        $currentDate = strtotime('+1 day', $currentDate);
    }
    
    return $workingDays;
}

// Example usage
$startDate = '2022-01-01';
$endDate = '2022-01-15';
$holidays = ['2022-01-01', '2022-01-06']; // Example holidays

echo getWorkingDays($startDate, $endDate, $holidays); // Output: 9