How can PHP be used to check for overlapping opening hours in a more efficient and elegant way?
To efficiently and elegantly check for overlapping opening hours in PHP, we can compare the start and end times of each set of opening hours with the start and end times of the target opening hours. By using the `DateTime` class in PHP, we can easily perform these comparisons and determine if there is any overlap.
function checkOverlap($openingHours1, $openingHours2) {
$start1 = new DateTime($openingHours1['start']);
$end1 = new DateTime($openingHours1['end']);
$start2 = new DateTime($openingHours2['start']);
$end2 = new DateTime($openingHours2['end']);
if ($start1 < $end2 && $start2 < $end1) {
return true; // Overlapping opening hours
}
return false; // No overlapping opening hours
}
// Example usage
$openingHours1 = ['start' => '09:00', 'end' => '17:00'];
$openingHours2 = ['start' => '10:00', 'end' => '18:00'];
if (checkOverlap($openingHours1, $openingHours2)) {
echo 'Opening hours overlap!';
} else {
echo 'Opening hours do not overlap.';
}
Keywords
Related Questions
- How can PHP variables such as $_GET['seite'] be properly utilized in pagination logic to display the correct page numbers?
- How can PHP scripts pass variable values to HTML form fields?
- What are some strategies for ensuring unique and clear variable names to prevent conflicts when using both POST and GET methods in PHP forms?