Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Add an item to the cart
- function add_item(array $cart, string $key, int $quantity, array $product) {
- if ($quantity > 0) {
- // If item already exists in cart, update quantity
- if (isset($cart[$key])) {
- $quantity += $cart[$key]['qty'];
- update_item($key, $quantity);
- return;
- } else {
- // Add item
- $item = array(
- 'name' => $product['name'],
- 'cost' => $product['cost'],
- 'qty' => $quantity,
- 'total' => $product['cost'] * $quantity,
- );
- $cart[$key] = $item;
- }
- }
- return $cart;
- }
- // Update an item in the cart
- $cart = [];
- function update_item(array $cart, string $key, int $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;
- }
- }
- return $cart;
- }
- // Get cart subtotal
- function get_subtotal(array $cart) {
- $subtotal = 0;
- foreach ($cart as $item) {
- $subtotal += $item['total'];
- }
- $subtotal_f = number_format($subtotal, 2);
- return $subtotal_f;
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment