I have an session cookie holding a multidimensional array called cart_array and I'm using a for each to loop through the inner arrays and a while loop get the key value pairs out.
I want to check if an item exists in the array based not only on the product id (pid) but several other variables such as color and size. Here's what I've come up with so far (but it only checks for the pid). How can I check for the other two variables?
Here are my variables
$_SESSION['cart_array'] = array(1 => array(
"pid" => $pid,
"quantity" => $quantity,
"color" => $color,
"size" => $size,
"title" => $title,
"product_type" => $product_type,
"price" => $price))
Here is the code for and while loop combination:
foreach($_SESSION['cart_array'] as $each_item) {
$index++;
while(list($key, $value) = each($each_item)) {
if($key == "pid" && $value == $pid) {
//That item is in the array
echo "This item is in the array";
} else {
echo "This item is not in the cart";
}
}
}
I would do something like this:
foreach($_SESSION['cart_array'] as $each_item) {
$index++;
$pidTest = false;
$colorTest = false;
$sizeTest = false;
while(list($key, $value) = each($each_item)) {
if($key == "pid" && $value == $pid) {
$pidTest = true;
}
if($key == "color" && $value == $color) {
$colorTest = true;
}
}
if ($pidTest && $colorTest && sizeTest)
{
echo "Item is in the cart";
}
else
{
echo "Nope";
}
}
You can handle this more elegantly and dynamically of course, but that's the basic logic you could use.
Have you tried:
foreach($_SESSION['cart_array'] as $item) {
$index++;
$pid_matches = $color_matches = $size_matches = false;
foreach($item as $key => $value) {
if($key == 'pid' && $value == $pid) {
$pid_matches = true;
}
elseif($key == 'color' && $value == $color){
$color_matches = true;
}
elseif($key == 'size' && $value == $size){
$size_matches = true;
}
}
if($pid_matches && $color_matches && $size_matches){
echo "This item is in the array";
}
else {
echo "This item is not in the cart";
}
}
If I got you right, this might help:
$_SESSION['cart_array'] = array(1 => array(
"pid" => $pid,
"quantity" => $quantity,
"color" => $color,
"size" => $size,
"title" => $title,
"product_type" => $product_type,
"price" => $price));
foreach($_SESSION['cart_array'] as $item) {
foreach($item as $key => $value) {
if( empty($value) ) {
echo "This item is not in the cart";
continue 2;
}
}
echo "This item is in the cart";
}
This will check every field of your item. If you need solution with set of exclusions or you need to compare elements with some set of values - let me know in comments.