I am using a $_SESSION array to store item description, quantity and price for items placed in a shopping cart. This all works dandy, here's the beginning portion of the code:
$quantity = 1;
// add first item from shop page
if(isset($_POST['add_item']) && (!isset($_SESSION['cart']))) {
$_SESSION['cart'] = array();
$_SESSION['cart'][$_POST['product_description']] = array('quantity' => $quantity, 'price' => $_POST['product_price']);
header("Location: http://website.com/cart.php");
}
This loads the $_SESSION['cart'] array with the appropriate information and when I foreach loop it in the cart page, I get the exact contents of my cart. All of this works as desired.
So now what I want to do is search the $_SESSION['cart'] array to determine if a specific item is in the $_SESSION['cart'] array, such as "iPhone case - Black".
I have tried various forms of echo $_SESSION['cart']['product_description'] and get nothing. When I print_r the array, I get this:
Array
(
[iPhone case - Black] => Array
(
[quantity] => 1
[price] => 9.49
)
)
Which is correct. Performing a var_dump yields the expected result:
array(1) {
["iPhone case - Black"]=>
array(2) {
["quantity"]=>
int(1)
["price"]=>
string(4) "9.49"
}
}
Certainly, if there is a better way to construct the array, I'm open to it.
All I want to do is find out if "iPhone case - Black" is in the $_SESSION['cart'] array and serve up the appropriate code based on the result.
I have tried if (in_array('iPhone case - Black', $_SESSION['cart'])) which yields nothing, and when I expand that to if (in_array('iPhone case - Black', $_SESSION['cart'][0])) or ...[1] or ...['product_description'] I receive the error:
Warning: in_array() expects parameter 2 to be array, null given in...
What am I missing that would simply let me check the $_SESSION['cart'] array to find the value, "iPhone case - Black"? Is my only option a foreach loop?
Many sincere thanks in advance!
UPDATE Code posting as per request from @rmmoul:
// add first item from shop page
if(isset($_POST['add_item']) && (!isset($_SESSION['cart']))) {
$_SESSION['cart'][] = array('product_description'=> $_POST['product_description'], 'quantity' => $quantity, 'price' => $_POST['product_price']);
header("Location: http://website.com/cart.php");
}
Returns this through a print_r:
Array
(
[0] => Array
(
[product_description] => iPhone case - Black
[quantity] => 1
[price] => 9.49
)
[1] => Array
(
[product_description] => iPhone case - Black
[quantity] => 1
[price] => 9.49
)
)