It alerts only one time because your while
condition is not correct.
Notice that the do { ... } while (condition)
loop will run at least once and continue as long as the condition
is true
, not until it becomes true
.
Change while($effective_date > $last_date)
to while($effective_date < $last_date)
:
$effective_date = '2020/09/03';
$last_date = '2020/12/03';
$last_date = new DateTime($last_date);
$effective_date = new DateTime($effective_date);
do{
$edate = $effective_date->format('Y/m/d');
echo "<script>alert('".$edate."');</script>";
$nxtdate = date('Y-m-d', strtotime("+1 months", strtotime($edate)));
$effective_date = new DateTime($nxtdate);
} while($effective_date < $last_date);
Ouput:
<script>alert('2020/09/03');</script><script>alert('2020/10/03');</script><script>alert('2020/11/03');</script>
Update
If you want the condition
to be checked before the statements inside the loop are executed, use the while
loop instead:
while ($effective_date < $last_date) {
$edate = $effective_date->format('Y/m/d');
echo "<script>alert('".$edate."');</script>";
$nxtdate = date('Y-m-d', strtotime("+1 months", strtotime($edate)));
$effective_date = new DateTime($nxtdate);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…