Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vk011's avatar
Level 1

Pushing to session array with custom key

If I have a session value which is an array, I know I can just push to it, but can I push to it with a custom key?

$request->session()->push('cart', $productInfo); // can $productInfo here have custom key somehow?
0 likes
3 replies
vk011's avatar
Level 1

Custom index, e.g. I wanna do something like this (which doesn't work)

$request->session()->push('cart', 'customKey' => $productInfo); 
Tanto's avatar
Tanto
Best Answer
Level 2

If your cart session variable is an associative array such as

  "cart" => array:4 [▼
    "a" => []
    "b" => []
    "c" => []
  ]

you won't be able to use ->push() since that expects a standard array. You could use instead

$cart = $request->session()->get('cart',[]);
$cart['customKey'] = 'new value';
$request->session()->put('cart', $cart);
  "cart" => array:4 [▼
    "a" => []
    "b" => []
    "c" => []
    "customKey" => "new value"
  ]

Please or to participate in this conversation.