0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPのforとwhileの違い

Posted at

どちらも反復処理を行うものだが、

・ forループ: 予めループ回数を決めておく場合に適している。
・ whileループ: ループ回数が決まっていない場合に適している。

■ forループ: 指定された回数分繰り返し処理を行う

for (初期化式; 条件式; 更新式) {
  // 繰り返し実行する処理
}

初期化式は、ループの最初に一度だけ実行される式。条件式は、ループが繰り返されるかどうかを評価する式であり、trueの場合にループが続行される。更新式は、繰り返し実行される処理の最後に実行される式。

例:

for ($i = 1; $i <= 5; $i++) {
    echo $i;
}

■ whileループ: 条件式がtrueであり続ける限り繰り返し処理を行う

while (条件式) {
  // 繰り返し実行する処理
}

例:

$i = 1;
while ($i <= 5) {
  echo $i;
  $i++;
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?