How can I optimize my PHP code for efficiently checking if a date is within the current week?

To efficiently check if a date is within the current week in PHP, you can use the DateTime class to get the start and end dates of the current week, and then compare the given date with these boundaries. This approach ensures accuracy and efficiency in determining if a date falls within the current week.

function isDateWithinCurrentWeek($date) {
    $givenDate = new DateTime($date);
    $startOfWeek = new DateTime('last sunday');
    $endOfWeek = new DateTime('next saturday');
    
    return $givenDate >= $startOfWeek && $givenDate <= $endOfWeek;
}

// Example usage
$date = '2022-10-05';
if (isDateWithinCurrentWeek($date)) {
    echo 'Date is within the current week.';
} else {
    echo 'Date is not within the current week.';
}