본문 바로가기

PHP

[PHP] 변수, 자료형, 조건문, 반복문

 - PHP 변수명(식별자)

 * PHP의 변수명은 문자, 숫자, '_', '$'로 만들 수 있습니다.
 * 변수명 앞에는 달러 기호를 붙여야 합니다. - 예) $abc, $school, $student
 * 변수명의 첫 문자는 숫자를 붙일 수 없습니다. - 예) $11, $100
 * 변수명은 대소문자를 구분합니다.



 - PHP 변수의 자료형(데이터 타입)

 * Integer - 정수형
 * Float - 실수형
 * String - 문자열
 * Boolean - 논리형
 * NULL - NULL




 - PHP 조건문 (if)

<?php
$t=date("H");
if ($t<"20")
  {
  echo "Have a good day!";
  }
?>

(예제 출처: PHP If...Else Statements)


(실행 결과)

Have a good day!



 - PHP 조건문 (if, elseif, else)

<?php
$t=date("H");
if ($t<"20")
  {
  echo "Have a good morning!";
  }

else if($t<"20")
  {
  echo "Have a good day!";
  }
else
  {
  echo "Have a good night!";
  }

?>

(예제 출처: PHP If...Else Statements)


(실행 결과)

Have a good day!



 - PHP 조건문 (Switch)

<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
  echo "Your favorite color is red!";
  break;
case "blue":
  echo "Your favorite color is blue!";
  break;
case "green":
  echo "Your favorite color is green!";
  break;
default:
  echo "Your favorite color is neither red, blue, or green!";
}
?>

(예제 출처: PHP Switch Statement)


(실행 결과)

Your favorite color is red!




 - PHP 반복문 (While)

<html>
<body>

<?php
$i=1;
while($i<=5)
  {
  echo "The number is " . $i . "<br>";
  $i++;
  }
?>

</body>
</html>

(예제 출처: PHP Looping While loops)


(실행 결과)

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5



 - PHP 반복문 (Do-While)

<html>
<body>

<?php
$i=1;
do
  {
  $i++;
  echo "The number is " . $i . "<br>";
  }
while ($i<=5);
?>

</body>
</html>

(예제 출처: PHP Looping While loops)


(실행 결과)

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6



 - PHP 반복문 (For)

<html>
<body>

<?php
for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "<br>";
  }
?>

</body>
</html>

(예제 출처: PHP Looping For loops)


(실행 결과)

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5



 - PHP 반복문 (Foreach)

<html>
<body>

<?php
$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br>";
  }
?>

</body>
</html>

(예제 출처: PHP Looping For loops)


(실행 결과)

one
two
three