Page 1 of 1

Creating a sum of all selected values

Posted: Mon Jan 04, 2010 10:18 am
by slaterino
Okay,
I think this might be quite basic but I am still trying to learn and not entirely sure how to do this!

I want to create a sum of all $qty values from the script below and then display this sum at the bottom. What is the best way of doing this?

Code: Select all

function printCart() {
    global $db;
    $cart = $_SESSION['cart'];
    if ($cart) {
        $items = explode(',',$cart);
        $contents = array();
        foreach ($items as $item) {
            $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
        }
        $output[] = '<form action="basket.php?action=update" method="post" id="cart">';
        $output[] = '<table width="600" align="center">';
        $output[] = '<tr><th>Item</th><th>Item Price</th><th>Quantity</th><th>Subtotal</th></tr>';
        foreach ($contents as $id=>$qty) {
            $sql = 'SELECT * FROM products WHERE Product_ID = '.$id;
            $result = $db->query($sql);
            $row = $result->fetch();
            extract($row);
            $output[] = '<tr>';
            $output[] = '<td align="center">'.$Common_Name.' ('.$Genus.')</td>';
            $output[] = '<td>&pound;'.$Price.'</td>';
            $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
            $output[] = '<td>&pound;'.(($Price) * $qty).'</td>';
            $total += (($Price) * $qty);
            $output[] = '</tr>';
        }
        $output[] = '</table>';
        $output[] = '<h2 align="right">Total: &pound;'.$total.'</h2>';
        $output[] = '</form>';
    }
    return join('',$output);
}

Re: Creating a sum of all selected values

Posted: Mon Jan 04, 2010 10:24 am
by AbraCadaver
If I understand correctly:

Code: Select all

$sum = 0;
foreach ($contents as $id=>$qty) {
    $sum = $sum + $qty;
    // rest of code
}

Re: Creating a sum of all selected values

Posted: Mon Jan 04, 2010 2:40 pm
by tr0gd0rr
Or just use array_sum()

Code: Select all

$sum = array_sum($contents);