kexxcream
kexxcream

Reputation: 5933

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'].

Upvotes: 2

Views: 309

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94652

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]);
}

Upvotes: 1

cb0
cb0

Reputation: 8613

You should have a look at the array_filter function for php.

It will take a array and a filter function. This filter function will be handed every element of your original array. In there check for your desired key.

If you return true in that function the final array will include the element, if false it will be excluded. There is a simple example in the docs.

Upvotes: 0

Related Questions