php - Removing item from Cart in Session | Codeigniter

Solution:

That's because your userdata is not the values themselves but the array containing them. You need to remove the item from the array and then save the array as the new userdata. Try something like this:

public function remove($id){
  $this->load->library('session');
  $list = $this->session->userdata('cart_items');

  if($list){
    foreach ($list as $item=>$value){
      if($id==$value['item_id']){
        unset($list[$item]);
        $list = array_values($list); // optional, reindex the array.
        break;
      }
    }

    $this->session->set_userdata('cart_items', $list);
  }

  redirect('Cart/index');

}

Answer

Solution:

public function remove($id){
        $this->load->library('session');
        $list = $this->session->userdata('cart_items');
        if($list){
            foreach ($list as $item=>$value){
                if($id==$value['item_id']){
                    $this->session->unset_userdata($value['item_id']);
                }
            }
        }
        redirect('Cart/index');

    }

View Code:-

<td>
<a href="<?= base_url().'user/remove/'.$value['item_id']; ?>">
  <button>REMOVE</button>
</a>
</td>

destroy or unset the value of the session?

 $this->session->unset_userdata('some_name');

and for multiple data you can:-

$array_items = array('username' => '', 'email' => '');

$this->session->unset_userdata($array_items);

and to destroy the session:-

$this->session->sess_destroy();

Note:- For more information about Session Class in Codeigniter,

https://codeigniter.com/userguide3/libraries/sessions.html

Source