How can PHP be used to calculate night surcharge based on work hours?
To calculate night surcharge based on work hours using PHP, you can first determine if the work hours fall within the night time range (typically between 10 PM and 6 AM). If the work hours do fall within this range, you can apply a surcharge rate to the total work hours to calculate the additional cost.
function calculateNightSurcharge($workHours, $surchargeRate) {
$nightStart = strtotime('22:00:00');
$nightEnd = strtotime('06:00:00');
$totalSurcharge = 0;
foreach ($workHours as $hour) {
$hourTimestamp = strtotime($hour);
if ($hourTimestamp >= $nightStart || $hourTimestamp < $nightEnd) {
$totalSurcharge += $surchargeRate;
}
}
return $totalSurcharge;
}
// Example usage
$workHours = ['08:00:00', '23:00:00', '03:00:00'];
$surchargeRate = 5; // $5 per hour surcharge for night hours
$nightSurcharge = calculateNightSurcharge($workHours, $surchargeRate);
echo "Night surcharge: $" . $nightSurcharge;