Creating a sum of all selected values

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
slaterino
Forum Commoner
Posts: 46
Joined: Fri Jul 11, 2008 10:50 am

Creating a sum of all selected values

Post 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);
}
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Creating a sum of all selected values

Post by AbraCadaver »

If I understand correctly:

Code: Select all

$sum = 0;
foreach ($contents as $id=>$qty) {
    $sum = $sum + $qty;
    // rest of code
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Creating a sum of all selected values

Post by tr0gd0rr »

Or just use array_sum()

Code: Select all

$sum = array_sum($contents);
Post Reply