Reputation: 1011
I am trying to validate whether or not an array is listed in an array. I am trying to add a product name and url to an session, the session will contain all the products visited by a visitor, but I don't want it to add the same product twice, hence the validation. So if the product is already in the array, I want it to do nothing, but if it doesn't already belong to the array, it needs to be added. This is as far as I got so far. The only issue seems to be the validation.
$viewed_product_url = $viewed_base.$_SERVER['REQUEST_URI'];
if(!isset($_SESSION['products'])) {
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
} else {
$found = false;
foreach($_SESSION['products'] as $each_item) {
while(list($key,$value)=each($each_item)) {
if($key == 'product' && $value == $products_name) {
$found = true;
}
}
}
if($found==false){
echo 'found';
$_SESSION['products'][] = array('product'=>$products_name,'url'=>$viewed_product_url);
}
}
these are the errors I am getting
Warning: Variable passed to each() is not an array or object in C:\xampp\htdocs\customers\msl\product.php on line 10
Warning: Variable passed to each() is not an array or object in C:\xampp\htdocs\customers\msl\product.php on line 10 found
So I just want to know how you can check if an array is already in an multivariate array. Or if there are any other alternatives to achieving what I want here.
Upvotes: 0
Views: 108
Reputation: 2316
$each_item
is not an array. That is the reason for the error.
Try this
$viewed_product_url = $viewed_base.$_SERVER['REQUEST_URI'];
if(!isset($_SESSION['products'])) {
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
} else {
$found = false;
if (in_array($viewed_product_url, $_SESSION['products'])) { {
$found = true;
}
}
}
if($found==false){
echo 'found';
$_SESSION['products'][] = array('product'=>$products_name,'url'=>$viewed_product_url);
} }
Upvotes: 0
Reputation: 780655
Change:
$_SESSION['products'] = array('product'=>$products_name,'url'=>$viewed_product_url);
to:
$_SESSION['products'] = array(array('product'=>$products_name,'url'=>$viewed_product_url));
so that you get a 2-dimensional array.
However, I think this is a poor data structure. You should make $_SESSION['products']
an associative array, whose key is the product name. So you add elements to it with:
$_SESSION['products'][$products_name] = $viewed_product_url;
and you find products with:
$found = isset($_SESSION['products'][$products_name]);
Upvotes: 1
Reputation: 20
is_array() function will help you.. http://php.net/manual/en/function.is-array.php
Upvotes: 0
Reputation: 28763
check with is_array
like
if(is_array($_SESSION['products']))
and then you can go with foreach
Upvotes: 0