Search code examples
phparrayssessionunset

Unset a specific session item based on value inside an array


Problem:

I have a session variable that consist of multiple array and each array has a set of values. I wish to unset the specific array that matches the value of a specific variable inside the session array.

Session construction:

enter image description here

PHP code:

$key = array_search($answers['evaluationnumber'], $_SESSION['stimuli']);

if ($key !== false) {
  unset($_SESSION['stimuli'][$key]);
  $_SESSION['stimuli'] = array_values($_SESSION['stimuli']);
}

I have double checked and I get the value 3841 from the variable $answers['evaluationnumber'].

Question:

How do I start digging into the array list to unset that specific key?

Desired output:

To be able to remove an array inside the session array called stimuli based on the value given in the variable $answers['evaluationnumber'].


Solution

  • If you only want to check the specific occurance on the session against $answers['evaluationnumber'] and as you say there will only ever be one occurance of the sub array in $_SESSION['stimuli'], this would seem the simplest way.

    if ( $_SESSION['stimuli'][0]['evaluationsnumber'] == $answers['evaluationnumber'] ) {
        unset($_SESSION['stimuli'][0]);
    }