What are some common pitfalls to avoid when implementing a workday calculation algorithm in PHP?
One common pitfall to avoid when implementing a workday calculation algorithm in PHP is not accounting for weekends and holidays. To solve this issue, you can create a function that checks if a given date is a weekend or holiday and adjust the calculation accordingly.
function isWeekend($date) {
$dayOfWeek = date('N', strtotime($date));
return ($dayOfWeek == 6 || $dayOfWeek == 7); // Saturday or Sunday
}
function isHoliday($date, $holidays) {
return in_array($date, $holidays);
}
function calculateWorkdays($startDate, $endDate, $holidays) {
$workdays = 0;
$currentDate = $startDate;
while ($currentDate <= $endDate) {
if (!isWeekend($currentDate) && !isHoliday($currentDate, $holidays)) {
$workdays++;
}
$currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
}
return $workdays;
}
// Example usage
$startDate = '2022-01-01';
$endDate = '2022-01-31';
$holidays = ['2022-01-01', '2022-01-17']; // New Year's Day, Martin Luther King Jr. Day
echo calculateWorkdays($startDate, $endDate, $holidays); // Output: 21