Understanding how Code works; Shopping Cart Total
<p>I've just begun learning how to create a shopping cart.</p>

<p>Came across this example:</p>

<pre><code>&lt;?php

   echo "Shopping cart:\n";

      $items = count($_SESSION['cart']);    
     {
         $total = 0;
    echo "&lt;table width=\"100%\" cellpadding=\"1\" border=\"1\"&gt;\n";
            echo "&lt;tr&gt;&lt;td&gt;Item Name&lt;/td&gt;&lt;td&gt;Quantity&lt;/td&gt;&lt;td&gt;Total&lt;/td&gt;&lt;/tr&gt;\n";
            foreach($_SESSION['cart'] as $itemid =&gt; $quantity)
            {
                $query = "SELECT description, price FROM items WHERE itemid = $itemid";
                $result = mysql_query($query);
                $row = mysql_fetch_array($result, MYSQL_ASSOC);
                $name = $row['name'];
                $price = $row['price'];

                $subtotal = $price * $quantity;
                $total += $subtotal;

    printf("&lt;tr&gt;&lt;td&gt;%s&lt;/td&gt;&lt;td&gt;%s&lt;/td&gt;&lt;td&gt;$%.2f&lt;/td&gt;&lt;/tr&gt;\n", $name, $quantity, $subtotal);
            }
            printf("&lt;tr&gt;&lt;td colspan=\"2\"&gt;Total&lt;/td&gt;&lt;td&gt;$%.2f&lt;/td&gt;&lt;/tr&gt;\n", $total);
            echo "&lt;/table&gt;\n";
       }

?&gt; 
</code></pre>

<p>The code works and I understand  most of it except for the "TOTAL or $total" part:</p>

<p>*$subtotal = $price * $quantity;
$total += $subtotal;*</p>

<p>As I said, it does work; if I place two items in the cart, for example: 5 pieces (quantity) of rocks that are $5 each and 2 pieces of pebbles that are $10 each, I get the SUBTOTALS on the respective table-rows of $25 for the widget and $20 for gadget. I'm assuming that</p>

<p>*$SUBTOTAL = $price * $quantity* -----  IS RESPONSIBLE FOR THIS, correct?</p>

<p>What I don't get is how it comes up with the TOTAL (which is correct--$45). </p>

<p>Which part of the code adds up the individual subtotals (i.e. $25 and $20)?</p>

<p>How does <strong>$total += $subtotal</strong>, work?</p>

<p>I'd like to understand how the code works/processes and not just take it because it works.</p>

<p>Thanks in advance.</p>
