Created
September 18, 2017 17:34
-
-
Save blackavec/e5db7e6a4fc94ea8ae04333550b02b33 to your computer and use it in GitHub Desktop.
Simple Example for add / remove cart items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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