Skip to content

Instantly share code, notes, and snippets.

@blackavec
Created September 18, 2017 17:34
Show Gist options
  • Save blackavec/e5db7e6a4fc94ea8ae04333550b02b33 to your computer and use it in GitHub Desktop.
Save blackavec/e5db7e6a4fc94ea8ae04333550b02b33 to your computer and use it in GitHub Desktop.
Simple Example for add / remove cart items
<?php
// Products items
[
"id" => 1,
"name" => "test"
"price" => 30
],
[
"id" => 2,
"name" => "test1"
"price" => 40
]
// Clicks on Add to cart - 2
function addToCart ($productId, $price, $quantity)
{
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
$cart = $_SESSION['cart'];
// Double check on product
foreach ($cart as $index => $value) {
if ($value['id'] === $productId) {
return $cart;
}
}
$cart = array_push($cart, [
"id" => $productId,
"price" => $price,
"quantity" => $quantity,
]);
return $_SESSION['cart'] = $cart;
}
// click to remove from cart - 2
function removeFromCart ($productId)
{
$cart = $_SESSION['cart'];
foreach ($cart as $index => $value) {
if ($value['id'] === $productId) {
unset($cart[$index]);
break;
}
}
return $_SESSION['cart'] = $cart;
}
// Cart items
$_SESSION['cart'] = [
0 => [
"id" => 1,
"name" => "test"
"price" => 30
],
1 => [
"id" => 2,
"name" => "test1"
"price" => 40
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment