Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

loops - Do While in php for two different dates

Want to alert Effective Date, till it meets the condition.

Code:-

$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);

It alerts only one time, but my expectation is it should be alerted 3 times

question from:https://stackoverflow.com/questions/66060108/do-while-in-php-for-two-different-dates

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...