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

sheldonscott's avatar

Removing (unsetting) an element from a Session array

I've done a bunch of Googling but have only found either very old answers that don't work with 5.5 or just don't work at all.

Within my app, users can add any number of Grade/Subject/Unit/Outcome (GSUO) combinations to a Session array (saved into a Session because I want to pass this data along through the different stages of a multi-step form across numerous pages before committing the data to the DB at the last step).

The GSUO data is being stored like this:

"gsuo" => array:5 [▼
    0 => "6~19~158~0"
    1 => "6~19~159~157"
    2 => "5~10~83~2525"
    3 => "4~9~75~0"
    4 => "3~19~154~52"
  ]

I want to use AJAX to delete a selected item from the array. Getting the ID for the clicked element or the value of the clicked element is not a problem. However, any code samples I've found online for removing an element from the array have not worked.

Here are some that I have tried:

public function step_3_delete_item($resource_type, Request $request)
{
    $removeByID = $request->input('itemIDToRemove');
    $removeByValue = $request->input('itemValueToRemove');

    $request->session()->forget('gsuo'.$removeByValue);
}

(I will only code block the $request portion now but assume the rest of the function is the same as above. I've also swapped $removeByID for $removeByValue in all examples.)

$gsuo = Session::get('gsuo');
unset($gsuo[$removeByID]);
Session::set('gsuo', $gsuo);
Session::put('gsuo', array_diff(Session::get('gsuo'), [$removeByID]));

Does anyone know how I can remove a value (for example, '3') from the gsuo array?

0 likes
0 replies

Please or to participate in this conversation.