LoginSignup
0
0

More than 3 years have passed since last update.

continue,breakに関して(PHP)

Posted at

continue,breakに関して

continueとbreakについてはそれぞれループ処理で使われる。

continueはある特定の条件をスキップして、そのままループ処理を続ける一方で、
breakはある特定の条件でループ処理を中断する。

実際のコードと出力結果については以下の通りとなる。

continue

continueは特定の条件で、ループをスキップして、そのままループを続ける。

<?php
for ($i = 1; $i <= 10; $i++) {
  if ($i % 3 === 0) {
    continue;
  }
  echo $i . PHP_EOL;
}
?>

出力結果

1
2
4
5
7
8
10

iが3の倍数になる条件でスキップしていて、3の倍数以外で、1から10までの数が出力されている。

break

breakの場合はある特定の条件でループ処理が止まる。

<?php

for ($i = 1; $i <= 10; $i++) {
  if ($i === 4) {
    break;
  }
  echo $i . PHP_EOL;
}
?>

出力結果

1
2
3

iが4になった場合にループ処理が止まり、1〜3の数字のみ出力される。

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