Skip to content
Advertisement

PHP on find the array with two keys equal to two values ​in the array and remove it from the array

I’m developing a shopping cart. I keep the basket in one session. I can add the product to the cart. But I don’t know how to remove product line from basket session.

Session structure; The session holds an array and the product arrays in it. I want to access the array I want to remove with two keys.

//Create basket session
$_SESSION['basket'] = [];

//Add a Product
$productArray = ['prodID' => '1', 'quantity' => '3'];
$_SESSION['basket'][] = $productArray;

//Post method comes with two variables (keys).
$prodID = $_POST['prodID'];
$quantity = $_POST['quantity'];

//How can I remove the array with keys equal to $prodID and $quantity within the session ?



Advertisement

Answer

First since your prodID should be unique in the session you can set it as the basket key

//Create basket session
$_SESSION['basket'] = [];

//Add a Product
$productArray = ['prodID' => '1', 'quantity' => '3'];
$_SESSION['basket'][$productArray['prodID']] = $productArray;

//Post method comes with two variables (keys).
$prodID = $_POST['prodID'];
$quantity = $_POST['quantity'];

//How can I remove the array with keys equal to $prodID and $quantity within the session ?
//Now you only need to update / replace the quantity here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement