3v4l.org

run code in 300+ PHP versions simultaneously
<?php function nextMonth($date, $increment) { $firstOfDateMonth = \DateTime::createFromFormat('Y-m-01', $date); $thirtyFirstOfDateMonth = \DateTime::createFromFormat('Y-m-t', $date); var_dump($thirtyFirstOfDateMonth); $thirtyFirstOfDateMonth = $thirtyFirstOfDateMonth->format('t'); $thirtyFirstOfNextMonth = clone $firstOfDateMonth; $thirtyFirstOfNextMonth->modify('+' . (int) $increment . ' month'); $thirtyFirstOfNextMonth = $thirtyFirstOfNextMonth->format('t'); $dayOfDateMonth = \DateTime::createFromFormat('Y-m-d', $date); $dayOfDateMonth = $dayOfDateMonth->format('d'); $dt = \DateTime::createFromFormat('Y-m-d', $date); $dt->modify('+' . (int) $increment . ' month'); if ($thirtyFirstOfNextMonth < $thirtyFirstOfDateMonth && $thirtyFirstOfNextMonth < $dayOfDateMonth) { $dt = clone $firstOfDateMonth; $dt->modify('+' . (int) $increment . ' month +' . $thirtyFirstOfNextMonth); } return $dt->format('Y-m-d'); } echo nextMonth('2009-12-31', 2),"\n"; echo nextMonth('2010-01-31', 1),"\n"; echo nextMonth('2010-01-05', 1),"\n"; echo nextMonth('2010-12-05', 1),"\n";

preferences:
28.58 ms | 402 KiB | 5 Q