How can overlapping time periods for rented items be prevented and managed in PHP code?
To prevent and manage overlapping time periods for rented items in PHP code, we can implement a check when a new rental is being added. We need to compare the start and end dates of the new rental with existing rentals to ensure there are no conflicts. If a conflict is found, we can either reject the new rental or adjust the dates accordingly.
// Check for overlapping time periods when adding a new rental
function addRental($newStart, $newEnd) {
// Assume $existingRentals is an array of existing rentals with 'start' and 'end' keys
foreach ($existingRentals as $rental) {
if (($newStart >= $rental['start'] && $newStart <= $rental['end']) || ($newEnd >= $rental['start'] && $newEnd <= $rental['end'])) {
// Overlapping time period found, handle accordingly (e.g. reject rental or adjust dates)
return false;
}
}
// If no overlapping time periods found, proceed with adding the new rental
// Your code to add the new rental here
return true;
}
// Example usage
$newStart = strtotime('2022-01-15');
$newEnd = strtotime('2022-01-20');
if (addRental($newStart, $newEnd)) {
// Rental added successfully
} else {
// Handle overlapping time periods
}