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
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
object(DateTime)#2 (3) { ["date"]=> string(26) "2022-10-10 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" } object(DateTime)#1 (3) { ["date"]=> string(26) "2022-10-15 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" }

preferences:
131.6 ms | 407 KiB | 5 Q