본문 바로가기
PHP

foreach

by 영감은어디에 2024. 10. 9.

<?php
$products = [
    'Toffee' => 2.99,
    'Mints'  => 1.99,
    'Fudge'  => 3.49,
];
?>

<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>

<?php
$best_sellers = ['Toffee', 'Mints', 'Fudge',];
?>

<?php foreach ($best_sellers as $product) { ?>
  <p><?= $product ?></p>
<?php } ?>

예제

<?php
$name = 'Ivy'; 
$greeting = 'Hello';       
if ($name) {     
    $greeting = 'Welcome back, ' . $name; 
}
$product = 'Lollipop';  
$cost    = 2;   
for ($i = 1; $i <= 10; $i++) {
    $subtotal   = $cost * $i;   
    $discount   = ($subtotal / 100) * ($i * 4); 
    $totals[$i] = $subtotal - $discount; 
}
?>

<?php require 'includes/header.php'; ?> 
  <p><?= $greeting ?></p>
  <h2><?= $product ?> Discounts</h2>
  <table>
    <tr>
      <th>Packs</th>
      <th>Price</th>
    </tr>
    <?php foreach ($totals as $quantity => $price) { ?>
    <tr>
      <td>
        <?= $quantity ?>pack<?= ($quantity === 1) ? '' : 's'; ?>
      </td>
      <td>
        $<?= $price ?>
      </td>
    </tr>
    <?php } ?>
  </table>

<?php include 'includes/footer.php' ?>

'PHP' 카테고리의 다른 글

sql  (0) 2024.10.11
date  (0) 2024.10.10
image file  (0) 2024.10.10
form  (0) 2024.10.10
내장함수, number, update  (0) 2024.10.10
object  (0) 2024.10.09
function  (0) 2024.10.09
PC에 XAMPP용 Imagick, ImageMagick 설치 하는법  (0) 2024.06.27