루프

minah moon·2023년 8월 2일

PHP

목록 보기
5/58
post-thumbnail

루프는 일련의 명령을 단 한 번 작성하고 고정된 횟수나 어떤 조건이 충족될 때까지 반복할 수 있게 한다.

루프의 종류는 다음과 같다

  • while 루프
  • do... while 루프
  • for 루프
  • foreach 루프

while 루프

while 루프는 조건이 true 값인 동안 구문을 반복한다.

<?php
$counter = 1;
$packs = 5;
$price = 1.99;
?>
<!DOCTYPE html>
<head>
  <title>Variables</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <h1>The Candy Store</h1>
  <h2>Prices for Multiple Packs</h2>
  <p>
    <?php
      while ($counter <= $packs) {
        echo $counter;
        echo ' packs cost $';
        echo $price * $counter;
        echo '<br>';
        $counter++;
      }
    ?>
  </p>
</body>
</html>

결과


do... while 루프

do... while 루프는 구문이 먼저 실행된 후에 조건을 검사한다는 점을 제외하면 while 루프와 비슷하다. 즉 조건에 대한 false라고 해도 구문은 최소한 한 번은 실행된다.

<?php
$packs = 5;
$price = 1.99;
?>
<!DOCTYPE html>
<head>
  <title>Variables</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <h1>The Candy Store</h1>
  <h2>Prices for Multiple Packs</h2>
  <p>
    <?php
      do {
        echo $packs;
        echo ' packs cost $';
        echo $price * $packs;
        echo '<br>';
        $packs--;
      } while ($packs > 0);
    ?>
  </p>
</body>
</html>

결과


for 루프

for 루프는 지정된 횟수만큼 일련의 구문을 반복한다. 이를 위해 카운터를 생성하고 루프가 실행될 때마다 카운드를 업데이트한다.

<?php
$price = 1.99;
?>
<!DOCTYPE html>
<head>
  <title>Variables</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <h1>The Candy Store</h1>
  <h2>Prices for Multiple Packs</h2>
  <p>
    <?php
    for ($i = 1; $i <= 10; $i++) { 
      echo $i;
      echo ' packs cost $';
      echo $price * $i;
      echo '<br>';
    }
    ?>
  </p>
</body>
</html>

결과


foreach 루프

foreach 루프는 배열의 각 요소에 대해 동일한 일련의 구문을 반복하게 한다.

<?php
$products = [
  'Toffe' => 2.99,
  'Mints' => 1.99,
  'Fudge' => 3.49,
];
?>
<!DOCTYPE html>
<head>
  <title>Variables</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <h1>The Candy Store</h1>
  <h2>Price List</h2>
  <table>
    <tr>
      <th>Item</th>
      <th>Price</th>
    </tr>
    <?php foreach ($products as $item => $price) { ?>
      <tr>
        <td><?= $item ?></td>
        <td>$<?= $price ?></td>
      </tr>
    <?php } ?>
  </table>
</body>
</html>

결과






출처 - 존 두켓, <백엔드 프로그래밍을 위한 PHP & MySQL>, Jpub, 2022

0개의 댓글