Empty shopping cart returns Invalid argument supplied for foreach()

Asked

Viewed 93 times

0

Whenever the shopping cart is empty, I open it and show the errors. But if I buy a product it disappears.

How do I fix it ?

Warning: Invalid argument supplied for foreach() in ...carrinho.php on line 152

foreach($_SESSION['monalisa_produto'] as $id => $qtd){
    $total_frete_produtos += $_SESSION['valor_frete_'.$id]*$qtd;
}

Warning: Invalid argument supplied for foreach() in ...carrinho.php on line 93

foreach($_SESSION['monalisa_produto'] as $id => $qtd){  
    $_SESSION['valor_frete_'.$id] = str_replace(",",".",$_SESSION['valor_frete_'.$id]);
    $_SESSION['valor_frete'] += $_SESSION['valor_frete_'.$id];  
}

I saw a post that said to put one if before the foreach, it would be right ?

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    ....
}

1 answer

1


The mistake happens because $_SESSION['monalisa_produto'] is not defined yet, or has a non-extendable value. You can use:

if (isset($_SESSION['monalisa_produto']) && is_array($_SESSION['monalisa_produto']))) {
    // foreach
}
  • Note: this code will not work if you are using something other than array to store the items in the cart, but I do not believe that is your case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.