3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Add days without specific days of the week * * @param DateTime $startDate start Date * @param int $days number of days * @param array $withoutDays array with elements "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun" * @return DateTime */ function addDaysWithout(DateTime $startDate ,int $days, array $withoutDays = []) : DateTime { //validate $withoutDays $validWeekDays = 7 - count($withoutDays); $validIdentifiers = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun"]; if($validWeekDays <= 0 OR $withoutDays != array_intersect($withoutDays,$validIdentifiers)){ $msg = 'Invalid Argument "'.implode(',',$withoutDays).'" in withoutDays'; throw new \InvalidArgumentException($msg); } $start = clone $startDate; $fullWeeks = (int)($days/$validWeekDays)-1; if($fullWeeks > 0){ $start ->modify($fullWeeks.' weeks'); $days -= $fullWeeks * $validWeekDays; } while($days){ $start->modify('+1 Day'); if(!in_array($start->format('D'),$withoutDays)){ --$days; } } return $start; } $start = date_create('2022-09-05'); $dt = addDaysWithout($start,30,["Sun"]); var_dump($dt); //object(DateTime)#3 (3) { ["date"]=> string(26) "2022-10-10 00:00:00.000000" $start = date_create('2022-09-05'); $dt = addDaysWithout($start,30,["Mon","Sun"]); var_dump($dt); //object(DateTime)#3 (3) { ["date"]=> string(26) "2022-10-15

preferences:
26.83 ms | 408 KiB | 5 Q