4
4

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

PHPのループ操作:continue, break

Last updated at Posted at 2014-03-30

最近、コードを書いていて使ったので共有なのですが、for文などのループ操作にcontinueやbreakを使うことがあると思います。
こんな感じ。

for ($i = 0; $i < 10; $i++) {
     if ($i === 5) continue;
     var_dump($i);
}

簡単な場合は良いのですが、for文の中にfor文があったりする場合、結構混乱すると思います。
そんなときは、continueやbreakの後に数字を挿入すると、どこまでcontinue、breakするのか指定することができます。
"continue;"は1つ分のネスト、"continue 2;"は2つ分のネスト・・・というように使えます。

下記は、ちょっと長いですが、私がInterestingDigitsという課題に取り組んだ時のコードです。

public function digits($base) {
    $results = [];

    for ($i = 2; $i < 1000; $i++) {

        for ($j = 1; $j < 1000; $j++) {

            $sum = 0;

            foreach (str_split(base_convert($i * $j, 10, $base)) as $value) {
                $sum += base_convert($value, $base, 10);
            }

            if ($sum % $i !== 0) continue 2;

            if (strlen($i * $j) >= 3) {
                if ($j !== 1) $results[] = $i;
                continue 2;
            }
        }
    }

    return $results;
}

たぶん、"continue 2;"を使ったことで、少し読みやすくなったのではないかなと思います。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?