<php
// Add an item to the cart
function cart_add_item(&$cart, $name, $cost, $quantity) {
$total = $cost * $quantity;
$item = array(
$name, 'cost' => $cost, 'qty' => $quantity, 'total' => $total
);
$cart[] = $item;
}
// Update an item in the cart
function cart_update_item(&$cart, $key, $quantity) {
if (isset($cart[$key])) {
if ($quantity <= 0) {
unset($cart[$key]);
} else {
$cart[$key]['qty'] = $quantity;
$total = $cart[$key]['cost'] * $cart[$key]['qty'];
$cart[$key]['total'] = $total;
}
}
}
?>
// load the library
require_once('cart.php');
// create an array to store the cart
$cart = array();
// call methods from the library
cart_add_item($cart, 'Flute', 149.95, 1);
cart_update_item($cart, 0, 2); // update the first item (key of 0)
$subtotal = cart_get_subtotal($cart);
// display the result
echo("<p>This subtotal is $" .$subtotal . "</p>\n");