웹프로그래밍 4주차 1차시 강의내용
PHP에는 조건문이 세 가지 있다.
1. if문 (Statement)
2. switch문 (Statement)
3. match (Expression, 수식, 계산식)
여기에서 Statement는 명령문들의 집합이고, Expression은 계산의 결과가 하나만 만들어지는 계산식이다.
1. if문 (Statement)
if (조건식) { 명령문; }
2. switch문 (Statement)
switch(변수 or 수식) {
case 값1 : 명령어; break;
case 값2 : 명령어; break;
case 값3 : 명령어; break;
default : 명령어;
}
- 값을 비교해서 매칭되는 것을 찾는다.
- 비교연산자는 '=='이다.
- break 키워드가 없으면 다음 케이스로 자동으로 내려간다 (그룹을 표현하기 위함)
- 문자열도 사용 가능하다
3. match (Expression, 수식, 계산식)
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
출력 :
string(19) "This food is a cake"
- '===' 연산자가 이용된다.
- 해당하는 케이스만 실행하고 매치가 끝나기 때문에, switch문의 break와 같은 키워드가 필요하지 않다.
- 같은 그룹을 표현하고 싶을 때는,
2, 3 => $a * 3;
처럼 콤마를 사용해주면 된다.
예제 (사칙연산 계산기)
calc.html파일
<!DOCTYPE html>
<html>
<head>
<title>사칙연산 계산기</title>
<meta charset = "utf-8">
</head>
<body>
<h1>사칙연산 계산기</h1>
<form action = "calc.php" method="get">
첫 번째 숫자 입력 <input type ="text" name = "no1"><br><br><br>
<input type = "radio" name="cal" value="+"> +
<input type = "radio" name="cal" value="-"> -
<input type = "radio" name="cal" value="*"> *
<input type = "radio" name="cal" value="/"> / <br><br><br>
두 번째 숫자 입력 <input type ="text" name = "no2"> =
<input type ="text" name = "result"><br><br><br>
<input type = "submit" value="계산" >
</form>
</body>
</html>
calc.php파일 (if문 이용)
<?php
# 입력양식의 값 읽기
$no1 = $_GET['no1']; // GET[입력양식의 name과 같은 값 작성]
$cal = $_GET['cal'];
$no2 = $_GET['no2'];
$result = $_GET['result'];
# 수식 계산하고 답 체크
if($cal == '+') $answer = $no1 + $no2;
elseif($cal == '-') $result = $no1 - $no2;
elseif($cal == '*') $result = $no1 * $no2;
else $answer = $no1 / $no2;
# 정답 출력
if($result == $answer) echo "<h3>정답입니다.</h3>";
else echo "<h3>오답입니다.</h3>";
echo "<h4>$no1 $cal $no2 = $answer</h4>";
?>
calc.php파일 (switch문 이용)
<?php
# 입력양식의 값 읽기
$no1 = $_GET['no1']; // GET[입력양식의 name과 같은 값 작성]
$cal = $_GET['cal'];
$no2 = $_GET['no2'];
$result = $_GET['result'];
switch($cal) { // if문보다 switch문이 더 직관적이다 (가독성이 높음)
case '+' : $answer = $no1 + $no2; break;
case '-' : $answer = $no1 - $no2; break;
case '*' : $answer = $no1 * $no2; break;
default : $answer = $no1 / $no2;
}
# 정답 출력
if($result == $answer) echo "<h3>정답입니다.</h3>";
else echo "<h3>오답입니다.</h3>";
echo "<h4>$no1 $cal $no2 = $answer</h4>";
?>
참고
https://php.365ok.co.kr/control-structures.match.php
LIST
'📖 Coding Study > 웹 프로그래밍' 카테고리의 다른 글
2023.05.01 월 (DB) (0) | 2023.05.01 |
---|---|
2023.04.04 화 (PHP 다차원 배열) (0) | 2023.04.04 |
2023.04.03 월 (PHP 배열) (0) | 2023.04.03 |
2023.03.28 화 (PHP 반복문, breakㆍcontinue 키워드, 배열) (0) | 2023.03.28 |
2023.03.14 화 (PHP 실습) (0) | 2023.03.14 |