PHP / 조건문 / if, elseif, else

if

설명

if로 조건을 만족할 때 실행할 작업을 정한다.

문법

if ( condition ) {
  statement;
}

condition이 TRUE이면 statement을 실행하고, FALSE이면 실행하지 않는다.

중괄호 대신 콜론과 endif를 이용할 수도 있다.

if ( condition ):
  statement;
endif;

예제

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Coding Factory</title>
    <style>
      p {
        font-family: "Consolas", monospace;
        font-style: italic;
        font-size: 1.3em;
      }
    </style>
  </head>
  <body>
    <?php
      $var = 15;
      if ( $var > 10 ) {
        echo "<p>var is greater than 10.</p>";
      }
    ?>
  </body>
</html>
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Coding Factory</title>
    <style>
      p {
        font-family: "Consolas", monospace;
        font-style: italic;
        font-size: 1.3em;
      }
    </style>
  </head>
  <body>
    <?php
      $var = 15;
      if ( $var > 10 ) :
    ?>
      <p>var is greater than 10.</p>
    <?php
      endif;
    ?>
  </body>
</html>

if, else

설명

if로 조건을 만족할 때 실행할 작업을, else로 조건을 만족하지 않을 때 실행할 작업을 정한다.

문법

if ( condition ) {
  statement1;
} else {
  statement2;
}

condition이 TRUE이면 statement1을 실행하고, FALSE이면 statement2를 실행한다.

중괄호 대신 콜론과 endif를 사용할 수도 있다.

if ( condition ):
  statement1;
else:
  statement2;
endif;

예제

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Coding Factory</title>
    <style>
      p {
        font-family: "Consolas", monospace;
        font-style: italic;
        font-size: 1.3em;
      }
    </style>
  </head>
  <body>
    <?php
      $var1 = 15;
      $var2 = 5;
      if ( $var1 > 10 ) {
        echo "<p>var1 is greater than 10.</p>";
      } else {
        echo "<p>var1 is not greater than 10.</p>";
      }
      if ( $var2 > 10 ) {
        echo "<p>var2 is greater than 10.</p>";
      } else {
        echo "<p>var2 is not greater than 10.</p>";
      }
    ?>
  </body>
</html>
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Coding Factory</title>
    <style>
      p {
        font-family: "Consolas", monospace;
        font-style: italic;
        font-size: 1.3em;
      }
    </style>
  </head>
  <body>
    <?php
      $var1 = 15;
      $var2 = 5;
      if ( $var1 > 10 ) :
    ?>
    <p>var1 is greater than 10.</p>
    <?php
      else :
    ?>
    <p>var1 is not greater than 10.</p>
    <?php
      endif;
      if ( $var2 > 10 ) :
    ?>
    <p>var2 is greater than 10.</p>
    <?php
      else :
    ?>
    <p>var2 is not greater than 10.</p>
    <?php
      endif;
    ?>
  </body>
</html>

if, elseif, else

설명

if와 elseif로 여러 조건을 만든 후 각 조건에 만족할 때 실행할 작업을 정한다. 모든 조건을 만족하지 않을 때 실행할 작업은 else로 정한다.

문법

if ( condition1 ) {
  statement1;
} elseif ( condition2 ) {
  statement2;
} else {
  statement3;
}
  1. condition1이 TRUE이면 statement1을 실행하고 조건문을 빠져나온다.
  2. condition1이 FALSE이고 condition2가 TRUE이면 statement2를 실행하고 조건문을 빠져나온다.
  3. condition1과 condition2가 모두 FALSE이면 statement3을 실행한다.

elseif는 여러 번 사용할 수 있으며, else는 필수가 아니므로 사용하지 않아도 된다.

중괄호 대신 콜론과 endif를 사용할 수도 있다.

if ( condition1 ):
  statement1;
elseif ( condition2 ):
  statement2;
else:
  statement2;
endif;

예제 1

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Coding Factory</title>
    <style>
      p {
        font-family: "Consolas", monospace;
        font-style: italic;
        font-size: 1.3em;
      }
    </style>
  </head>
  <body>
    <?php
      $var = 25;
      if ( $var > 10 ) {
        echo "<p>var is greater than 10.</p>";
      } elseif ( $var > 20 ) {
        echo "<p>var is greater than 20.</p>";
      } elseif ( $var > 30 ) {
        echo "<p>var is greater than 30.</p>";
      } else {
        echo "<p>var is not greater than 10.</p>";
      }
    ?>
  </body>
</html>

예제 2

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>Coding Factory</title>
    <style>
      p {
        font-family: "Consolas", monospace;
        font-style: italic;
        font-size: 1.3em;
      }
    </style>
  </head>
  <body>
    <?php
      $var = 25;
      if ( $var < 10 ) {
        echo "<p>var is less than 10.</p>";
      } elseif ( $var > 10 and $var < 20 ) {
        echo "<p>var is greater than 10 and less than 20.</p>";
      } elseif ( $var > 20 and $var < 30 ) {
        echo "<p>var is greater than 20 and less than 30.</p>";
      }
    ?>
  </body>
</html>

같은 카테고리의 다른 글
PHP / include(), include_once(), require(), require_once() / 외부 파일 포함하는 함수

PHP / include(), include_once(), require(), require_once() / 외부 파일 포함하는 함수

여러 파일에 공통적으로 사용하는 코드는 별도의 파일로 만든 후 각 파일에서 불러오는 것이 좋습니다. 코드의 양이 줄어들고, 수정이 용이하기 때문입니다. 외부 파일을 포함하는 함수는 네 가지가 있습니다. include 같은 파일 여러 번 포함 가능 / 포함할 파일이 없어도 다음 코드 실행 include_once 같은 파일 한 번만 포함 / 포함할 파일이 없어도 다음 코드 실행 require 같은 파일 ...

PHP / 조건문 / if, elseif, else

PHP / 조건문 / if, elseif, else

if 설명 if로 조건을 만족할 때 실행할 작업을 정한다. 문법 if ( condition ) { statement; } condition이 TRUE이면 statement을 실행하고, FALSE이면 실행하지 않는다. 중괄호 대신 콜론과 endif를 이용할 수도 있다. if ( condition ): statement; endif; 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>Coding Factory</title> <style> ...

PHP / 변수 / 유동 변수(변수 안에 변수) 만드는 방법

PHP / 변수 / 유동 변수(변수 안에 변수) 만드는 방법

변수를 일정 규칙에 따라 자동으로 만들어야 할 때가 있다. 이런 변수를 유동 변수라고 하는 거 같은데, 공식 용어인지는 잘 모르겠다. 유동 변수를 만들려고 하면 변수 이름을 만들 때 변수를 넣어야 한다. 예를 들어 변수 이름에 $var라는 이름을 넣고 싶다면 다음과 같이 한다. ${$var} 아래는 변수 이름에 일련 번호를 붙이는 예제이다. 배열의 값을 일련 ...

PHP / 함수 / mysqli_connect() / MySQL server 또는 MariaDB Server에 연결하는 함수

PHP / 함수 / mysqli_connect() / MySQL server 또는 MariaDB Server에 연결하는 함수

개요 mysqli_connect는 MySQL server 또는 MariaDB Server에 연결하는 함수입니다. 문법 mysqli_connect( host, username, password, databasename, port, socket ); 예제 1 데이터베이스 서버에 연결하고 결과를 출력합니다. <?php $jb_connect = mysqli_connect( 'localhost', 'jb', '1234', 'employees' ); var_dump( $jb_connect ); ?> 연결에 성공한 경우입니다. 연결에 실패하면 false를 반환합니다. 예제 2 연결에 성공하면 Success, 실패하면 Failure를 출력합니다. <!doctype html> <html lang="ko"> <head> ...

PHP / 회원 관리 / 세션(SESSION) 추가하기, 로그아웃 페이지

PHP / 회원 관리 / 세션(SESSION) 추가하기, 로그아웃 페이지

login.php 로그인 한 상태인지 로그인 하지 않은 상태인지 파악하기 위해 login-ok.php로 넘어가기 전에 세션을 시작합니다. 그리고 username을 $_SESSION에 담습니다. <?php $username = $_POST; $password = $_POST; if ( !is_null( $username ) ) { $jb_conn = mysqli_connect( 'localhost', 'codingfactory', '1234qwer', 'codingfactory.net_example' ...

PHP / 함수 / empty() / 비어있는 변수인지 검사하는 함수

PHP / 함수 / empty() / 비어있는 변수인지 검사하는 함수

개요 empty로 변수가 비어있는지 검사합니다. PHP 4 이상에서 사용할 수 있습니다. 문법 empty( $var ) $var가 비어있는지 검사하고, 비어있다면 TRUE, 비어있지 않다면 FALSE를 반환합니다. 다음을 비어있는 것으로 판단합니다. "" (빈 문자열) 0 (정수 0) "0" (문자열 0) NULL FALSE array() (빈 배열) var $var; (클래스 안에서 값 없이 선언된 변수) 예제 <!doctype html> <html lang="ko">   <head>     <meta charset="utf-8">     <title>Coding Factory</title>     <style>       p {         font-family: "Times New ...

PHP / 함수 / strip_tags() / 문자열에서 HTML 태그와 PHP 태그 제거하는 함수

PHP / 함수 / strip_tags() / 문자열에서 HTML 태그와 PHP 태그 제거하는 함수

개요 strip_tags는 문자열에서 HTML 태그와 PHP 태그 제거하는 함수입니다. PHP 4 이상에서 사용할 수 있습니다. 문법 strip_tags ( string $str ) allowable_tags로 제거하지 않을 태그를 정할 수 있습니다. 예를 들어 strip_tags( '<p>Lorem <strong>Ipsum</strong></p>' ) 는 모든 태그를 제거합니다. strip_tags( '<p>Lorem <strong>Ipsum</strong></p>', '<strong>' ) 은 strong 태그를 제외한 나머지 태그를 제거합니다. 예제 <!doctype html> <html lang="ko"> <head> ...

PHP / 다른 페이지로 리디렉션(Redirection)하는 방법

PHP / 다른 페이지로 리디렉션(Redirection)하는 방법

여러 가지 이유로 a.php로 접속했을 때 b.php로 자동 이동하게 만들어야 할 경우가 있습니다. 이를 보통 리디렉션(Redirection)이라고 하는데, PHP에서는 다음과 같은 코드로 리디렉션을 구현할 수 있습니다. 다음과 같은 코드가 있는 페이지에 접속하면 https://www.codingfactory.net로 이동합니다. header( 'Location: https://www.codingfactory.net' ); 일정 시간 지난 후에 이동시키고 싶다면 sleep() 함수를 이용하세요. 다음은 5초 후 이동시키는 코드입니다. sleep( 5 ); header( ...

PHP / 두 날짜 사이의 기간(차이) 구하는 방법

PHP / 두 날짜 사이의 기간(차이) 구하는 방법

두 날짜 사이의 차이 구하기 시작하는 날짜를 변수에 담는다. $from = new DateTime( '2022-01-01' ); 끝나는 날짜를 변수에 담는다. $to = new DateTime( '2022-03-31' ); diff 또는 date_diff로 차이를 구한다. echo $from -> diff( $to ) -> days; echo date_diff( $from, $to ) -> days; 2022년 1월은 31일, 2월은 28일, 3월은 31일로 총 90일이다. 위의 방식으로 계산하면 89일이 ...

PHP / Ubuntu / Apache / HTML 확장자에도 PHP 코드 인식되도록 설정하는 방법

PHP / Ubuntu / Apache / HTML 확장자에도 PHP 코드 인식되도록 설정하는 방법

Ubuntu에 Apache로 웹서버를 만들고 PHP를 사용할 수 있게 만든 경우, 기본적으로 확장자가 php인 경우에만 PHP 코드를 인식합니다. 만약 확장자가 html일 때로 PHP 코드가 인식되도록 하고 싶다면, Apache 설정을 바꿔줘야 합니다. /etc/apache2/mods-enabled/mime.conf 파일을 엽니다. 다음 코드를 추가합니다. AddType application/x-httpd-php .html 확장자가 htm인 경우에도 PHP를 인식하도록 하고 싶다면 다음처럼 합니다. AddType application/x-httpd-php .html .htm 웹서버를 다시 로드합니다. service apache2 ...