LoginSignup
1
0

More than 5 years have passed since last update.

[PHP]while文に対してdo while文を使うメリット

Posted at

while文の例

<?php
$i = 0;
while($i < 10){
    echo $i;
    $i ++;
}
// => 0123456789

まず\$iに0を代入し、while内で、$iが10になるまで出力されている。

do while文の例

<?php
$i = 0;
do{
    echo $i;
    $i++;
}while($i < 10);
// => 0123456789

こちらはdo while文。whileよりも先に、$iが出力されている。

たとえば$i=100なら

<?php
$i = 0;
while($i < 10){
    echo $i;
    $i ++;
}
// => (表示されない)

while文の場合、\$iが100なので、while文の1週目から「 \$i < 10 」を満たしているので、while内が処理されず、$iの出力がされない。

<?php
$i = 100;
do{
    echo $i;
    $i++;
}while($i < 10);
// => 100

do while文の場合、whileが最後に来ているので、1週目の$iが出力される。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0