LinkedNestBlog

PHP 문법 : 반복문

by 이진원Dev
PHP 문법 : 반복문


ref.] 생활코딩 > PHP > PHP 기본수업 > 반복문
https://opentutorials.org/course/62/5123

  • 반복문 문법
    1. while
      • 형태
        while( 조건 ) {
             ...
        }
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        <?php
            $i = 0;
            while($i < 10){
                echo 'say hello';
                echo '<br/>';
                $i++;
            }
        ?>
        cs
      • 결과
        say hello
        say hello
        say hello
        say hello
        say hello
        say hello
        say hello
        say hello
        say hello
        say hello
    2. for
      • 형태
        for (초기화 변수 ; 반복 조건 ; 변수 증가) {
             ...	
        }
      • 소스코드
        1
        2
        3
        4
        5
        6
        <?php
            for ( $j = 0 ; $j < 10 ; $j++ ) {
                echo 'say hello, too';
                echo '<br/>';
            }
        ?>
        cs
      • 결과
        say hello, too
        say hello, too
        say hello, too
        say hello, too
        say hello, too
        say hello, too
        say hello, too
        say hello, too
        say hello, too
        say hello, too
  • 반복문 흐름 제어
    1. break
      • 설명
        • 반복작업을 중간에 중단시키고 싶을 때 사용.
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        <?php
            for ( $j = 0 ; $j < 10 ; $j++ ) {
                if($j == 5){
                    break;
                }
                echo 'say hello, too'.$j;
                echo '<br/>';
            }
        ?>
        cs
      • 결과
        say hello, too0
        say hello, too1
        say hello, too2
        say hello, too3
        say hello, too4
    2. continue
      • 설명
        • 특정 조건의 실행은 제외하고 싶을 때 사용.
      • 소스코드
        1
        2
        3
        4
        5
        6
        7
        8
        9
        <?php
            for ( $j = 0 ; $j < 10 ; $j++ ) {
                if($j == 5){
                    continue;
                }
                echo 'say hello, too'.$j;
                echo '<br/>';
            }
        ?>
        cs
      • 결과
        say hello, too0
        say hello, too1
        say hello, too2
        say hello, too3
        say hello, too4
        say hello, too6
        say hello, too7
        say hello, too8
        say hello, too9
PHP 문법 : 반복문 · LinkedNest Blog