Search code examples
phpsymfonysymfony5

Effective way to unset session array in php/symfony


php unset is working but on reload the session data is still there: I'm building simple addtocart and remove from cart in php/symfony5, but I'm unable to unset the array from multi dimension array in symfony session.

^ array:3 [▼
0 => array:1 [▼
  "items" => array:4 [▼
    0 => 9
    1 => "Dry fruit"
    2 => "1234"
    3 => "250g"
  ]
]
1 => array:1 [▼
   "items" => array:4 [▼
   0 => 8
   1 => "Pumpkin"
   2 => "123"
   3 => "x"
 ]

]

This is my cart controller:

        $basket = $session->get('basket',[]);
    dump($basket);
    $size = $session->get('size');
    if($request->isMethod('POST')){
       $id = $request->request->get('0');
       foreach($basket as $key => $value){
           if($value['items'][0] == $id){
            unset($basket[$key]['items']);
            dd($basket);
            //$session->set('basket',[]);
            //return $this->redirectToRoute('cart');
           }
       }

    }

On the above code when I click remove button in twig and when dd($basket) is done the array is empty like below:

^ array:3 [▼
0 => [] //empty
1 => array:1 [▼
"items" => array:4 [▼
  0 => 8
  1 => "Pumpkin"
  2 => "123"
  3 => "x"
]

]

But, when I comment dd($basket) and page is reloaded the array is as it is like before(seems reverted idk) and if I uncomment $session->set('basket',[]); everything is empty.

what I want to achieve here is, how to remove array from session multi dimension array?


Solution

  • You simply need to set the session variable to the updated $basket value.

    // get a copy of the basket from the session
    $basket = $session->get('basket',[]);
    
    // do whatever to update $basket here
    
    // overwrite the basket in the session
    $session->set('basket', $basket);
    
    // then return a Response