본 게시글은 유튜브 생활코딩 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.

생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.

생활코딩 유튜브

 

생활코딩

일반인에게 프로그래밍을 알려주는 온라인/오프라인 활동 입니다.

www.youtube.com

생활코딩 사이트

 

생활코딩

hello world 생활코딩의 세계에 오신 것을 환영합니다. 생활코딩은 일반인들에게 프로그래밍을 알려주는 무료 온라인, 오프라인 수업입니다.  어떻게 공부할 것인가를 생각해보기 전에 왜 프로그래밍을 공부하는 이유에 대한 이유를 함께 생각해보면 좋을 것 같습니다. 아래 영상을 한번 보시죠. 온라인 강의 소개 입문자의 가장 큰 고충은 '무엇을 모르는지 모르는 상태'일 겁니다. 온라인에는 프로그래밍을 익히는 데 필요한 거의 모든 정보가 있지만, 이 지식들은

opentutorials.org

생활코딩 WEP3 PHP & MySQL을 수강하기 위한 선수과목인

WEB2 - PHPDATABASE2 - MySQL에 대한 수강 기록입니다.

수강 일정은 야학의 수강계획표에 따릅니다.


#0.

제어문 중 조건문을 PHP에서 어떻게 사용하는지 알아 보자.

 

#1.

조건문을 배우기에 앞서서 Boolean과 비교연산자에 대해서 알아보는 시간입니다. 

 

PHP의 Boolean Type

 

PHP: Booleans - Manual

Function to sort array by elements and count of element (before php 5.3) (not use Lambda Functions, and Closures) count($b["'.$sortField.'"])) return 1*'.$order.';            if(count($a["'.$sortField.'"]) < count($b["'.$sortField.'"])) return -1*'.$

www.php.net

PHP의 비교 연산자

 

PHP: Comparison Operators - Manual

When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words: To answer that question, use: A related, but more strict problem, is if you need to ensure that two arrays contain

www.php.net

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <h1>Comparison Operators &amp; Boolean data type </h1>
    <h2>1==1</h2>
    <?php
    var_dump(1==1);
    ?>
    <h2>1>1</h2>
    <?php
    var_dump(1>1);
    ?>
    <h2>1>=1</h2>
    <?php
    var_dump(1>=1);
    ?>
  </body>
</html>

Boolean과 비교 연산자에 대하여 알고 있다면, 이번 강의는 넘어가도 좋을 것 같다.

다만, 비교 연산자의 경우엔 언어마다 정의가 다르니

(외울 필요는 없다고 생각하지만) 잠깐 체크하고 넘어가도록 하자.

 

#2.

PHP의 조건문 ( if , else , elseif/else if)

 

PHP: Control Structures - Manual

This is list is missing a link for:try ... catch ... finallyblocks. You will find this critical language construct hidden away in the "Exceptions" chapter.And, even though being very verbose and admittedly having useful code examples, that Exceptions chapt

www.php.net

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <h1>Conditional</h1>
    <h2>if</h2>
    <?php
    echo '1<br>';
    if(false) {
      echo '2-1<br>';
    } else {
      echo '2-2<br>';
    }
    echo '3<br>';
    ?>
  </body>
</html>

마찬가지로 기본적인 조건문의 형식에 대하여 알고 있다면, 이번 강의 역시 넘어가도 좋을 것 같다.

다른 언어들의 조건문과 PHP의 조건문은 거의 같다.

 

#3.

저번 시간(Day4)에 나타난 에러로 예습한 '아이디 값이 없는 경우' 를 이번 시간에 학습하고자 한다.

(사실 그럴 것 같았지만.. 에러창이 찝찝해서 구글링으로 이미 해결했었다.)

지금 내가 짠 코드와 어떤 다른 방법으로 해결하는지 영상을 통해 복습해보도록 하자.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1><a href="/index.php">WEB</a><h1>
    <ol>
      <li><a href="index.php?id=HTML">HTML</a></li>
      <li><a href="index.php?id=CSS">CSS</a></li>
      <li><a href="index.php?id=JavaScript">JavaScript</a></li>
    </ol>
    <h2>
      <?php
        $value = isset($_GET['id']) ? $_GET['id'] : '';
        echo $value;
       ?>
    </h2>
    <?php
    if($value){
      echo file_get_contents("data/".$value);
    }
     ?>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <li><a href="index.php?id=HTML">HTML</a></li>
      <li><a href="index.php?id=CSS">CSS</a></li>
      <li><a href="index.php?id=JavaScript">JavaScript</a></li>
    </ol>
    <h2>
      <?php
      if(isset($_GET['id'])){
        echo $_GET['id'];
      } else {
        echo "Welcome";
      }
      ?>
    </h2>
    <?php
    if(isset($_GET['id'])){
      echo file_get_contents("data/".$_GET['id']);
    } else {
      echo "Hello, PHP";
    }
     ?>
  </body>
</html>

가정문을 사용하는 형식이 조금 틀리긴 하지만 비슷한 방법으로 이를 해결했다.

여담이지만 내가 사용한 방식은 php에서 Ternary Operator라고 불린다.

PHP의 삼항 연산자 (ctrl+f : "Ternary Operator")

 

PHP: Comparison Operators - Manual

When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words: To answer that question, use: A related, but more strict problem, is if you need to ensure that two arrays contain

www.php.net

추가적인 설명이 필요하다면 이 곳이 잘 정리해놓은 것 같다.

 

Ternary Operator in PHP | How to use the PHP Ternary Operator | Codementor

This article on Ternary Operator in PHP will provide in-depth knowledge about the purpose of ternary operator and its advantages with examples.

www.codementor.io

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>

`A` ? `B` : `C` 

의 형태가 있을 때, `A`가 참이라면 `B`가 반환되고, 거짓이라면 `C`가 반환된다.

`B`를 생략한 `A1` ?: `C` 의 형태로 사용할 수 있는데 ,

이 경우는 `A`가 참이라면 `A`, 거짓이라면 `C`가 반환된다.

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't' prior to PHP 8.0.0
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, one can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

위의 설명처럼 삼중연산자는 중첩되어 사용 할 경우 PHP에서 그 성능을 보장할 수가 없단 단점이 있다.

따라서, 다시 생활코딩에서 강의한 코드로 돌아가도록 하겠다.

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기