Shopping cart Empty returns Invalid argument supplied for foreach ()

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 resolve this?

  

Warning: Invalid argument supplied for foreach () in ... cart.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 ... cart.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 a if before foreach , would it be correct?

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    ....
}
    
asked by anonymous 14.10.2017 / 10:14

1 answer

1

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

if (isset($_SESSION['monalisa_produto']) && is_array($_SESSION['monalisa_produto']))) {
    // foreach
}
    
14.10.2017 / 11:01