조건문을 이용한 프로그램 - IF문

1. if문

if (조건)

 문장;

또는

if (조건) {
 문장1;
 문장2;
 ...
 
}

- 조건이 TRUE이면 문장이 실행되고 FALSE이면 실행 되지 않는다.
- 조건은 TRUE이나 FALSE 중에 하나의 값으로 판별이 가능해야 한다.
- 다음 조건이 FALSE인 경우이다.
  * 블린언(Boolean)에서 FALSE인 경우
  * 조건의 값이 형식과 상관없이 0인 경우
  * 값나 지정된 변수가 없는 경우
  * 원소가 없는 배열이거나 빈 문자열인 경우


예제) 입력된 값 중에 큰 값을 출력한다.


test.html
<html>
 <head>
  <title> 입력 폼파일 </title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
 </head>
 <form method="post" action="test.php">
  A : <input type="text" name="a"><br>
  B : <input type="text" name="b"><br>
   <input type="submit" name="확인" value="확인">
   <input type="reset" value="취소"><br>
 </form>
</html>


test.php
<?php
 $a = $_POST["a"];
 $b = $_POST["b"];
 if($a>$b){
  echo "입력 값 중 큰 값은 \$a(".$a.")입니다.";
 }
 if($a<$b){
  echo "입력 값 중 큰 값은 \$b(".$b.")입니다.";
 }
 if($a==$b){
  echo "두 값이 동일합니다.";
 }

?>

test.html

test.php


입력 폼

||

==========================================================



if else 문


if (조건)
 문장;
else 
 문장;


또는


if (조건){
 문장1;
 문장2;
}else{
 문장1;
 문장2;
}


- 조건이 TRUE이면 if 절의 문장이 실행되고, FALSE이면 else절의 문장이 실행된다.
- 둘 중 하나를 선택하는 if문을 '분기문' 이라 부르기도 한다.


if else if 문


if(조건1){
 문장1;
}else if(조건2){
 문장1;
}else if(조건3){
 문장1;
}else{ //default
 문장1;
}


- 조건이 여러 개일 경우 각 조건에 해당하는 문장을 실행한다.
- 조건에 일치하는 경우가 없다면 default 문장을 실행한다.


score.html
<html>
 <head>
  <title> 학점 계산기 </title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
 </head>
 <h2>학점 계산기</h2>
 <form method="post" action="score.php">
  평균 점수 : <input type="text" name="score"><br><br>
     <input type="submit" name="확인" value="확인">
     <input type="reset" value="취소"><br>
 </form>
</html>


score.php
<?php
 $score = $_POST["score"];
 if($score>90){
  echo "당신의 학점은 A 입니다.";
 }else if($score>80){
  echo "당신의 학점은 B 입니다.";
 }else if($score>70){
  echo "당신의 학점은 C 입니다.";
 }else if($score>60){
  echo "당신의 학점은 D 입니다.";
 }else{
  echo "당신의 학점은 F 입니다.";
 }

?>

score.html

score.php

결과



'PHP' 카테고리의 다른 글

[PHP] 반복문(while, do..while, for)  (0) 2017.07.17
[PHP] 조건문 Switch  (0) 2017.07.04
[PHP] 연산자  (0) 2017.07.03
[PHP] 변수와 연산자 - 변수와 데이터 타입  (0) 2017.07.03
[PHP] Explode  (0) 2017.06.30

+ Recent posts