Guest User

Untitled

a guest
Nov 13th, 2026
42
0
177 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.34 KB | Source Code | 0 0
  1. <?php
  2. // Add an item to the cart
  3. function add_item(array $cart, string $key, int $quantity, array $product) {
  4.     if ($quantity > 0) {
  5.         // If item already exists in cart, update quantity
  6.         if (isset($cart[$key])) {
  7.             $quantity += $cart[$key]['qty'];
  8.             update_item($key, $quantity);
  9.             return;
  10.         } else {
  11.             // Add item
  12.             $item = array(
  13.                 'name' => $product['name'],
  14.                 'cost' => $product['cost'],
  15.                 'qty'  => $quantity,
  16.                 'total' => $product['cost'] * $quantity,
  17.             );
  18.             $cart[$key] = $item;
  19.         }
  20.     }
  21.     return $cart;
  22. }
  23.  
  24. // Update an item in the cart
  25. $cart = [];
  26. function update_item(array $cart, string $key, int $quantity) {
  27.     if (isset($cart[$key])) {
  28.         if ($quantity <= 0) {
  29.             unset($cart[$key]);
  30.         } else {
  31.             $cart[$key]['qty'] = $quantity;
  32.             $total = $cart[$key]['cost'] *
  33.                      $cart[$key]['qty'];
  34.             $cart[$key]['total'] = $total;
  35.         }
  36.     }
  37.     return $cart;
  38. }
  39.  
  40. // Get cart subtotal
  41. function get_subtotal(array $cart) {
  42.     $subtotal = 0;
  43.     foreach ($cart as $item) {
  44.         $subtotal += $item['total'];
  45.     }
  46.     $subtotal_f = number_format($subtotal, 2);
  47.     return $subtotal_f;
  48. }
  49. ?>
Advertisement
Add Comment
Please, Sign In to add comment