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 3 years have passed since last update.

PHPのループ処理でcontinue、breakを使ってみましょう☆

Posted at

☆continue☆


特定の処理の時にループをスキップするには

continueを使っていきます!

以下のfor文があったとします。

index.php
for ($i = 1; $i <= 5; $i++) {
    echo $i . PHP_EOL;
}

ターミナルに以下を入力します!
~$ php index.php

1〜5が出力されます!
~ $ php main.php
1
2
3
4
5
~ $ 

2だけとばしたいので continue を使います!

index.php
for ($i = 1; $i <= 5; $i++) {
    if ($i === 2) {         // 2のとき
    continue;
    }
    echo $i . PHP_EOL;
}

ターミナルで同じく以下を実行すると...
~$ php index.php

2だけとばされました!
~ $ php main.php
1
3
4
5
~ $ 

☆break☆


次はループを抜けたる為の break を使っていきます!

最初のfor文にbreakを追加します。

index.php
for ($i = 1; $i <= 5; $i++) {
    if ($i === 3) {      //3になったら抜ける
    break;
    }
    echo $i . PHP_EOL;
}

ターミナルに以下を入力します!

~$ php index.php

3になると処理が終わりました!
~ $ php main.php
1
2
~ $ 

処理をスキップする方法と、抜ける方法でした!


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?