Search code examples
phpsessionyiiyii2unset

Having trouble unsetting session variable in Yii2


I'm using Yii2 and I have just started working with sessions within it. I have read the documentation for them on the Yii site.

One thing I noticed is it is a bit hard to work with multi-dimensional arrays in sessions without using the standard superglobal $_SESSION and hence I have mainly been using that.

One thing I am having trouble doing though is unsetting a session variable.

Example:

if (!Yii::$app->session->isActive) {
    Yii::$app->session->open();
}

print_r($_SESSION['foo']);

if ($this->command == 'sample_action') {

    if (!isset($_SESSION['foo'][$this->some_id][$this->example_id])) {
        $_SESSION['foo'][$this->some_id][$this->example_id] = $this->example_id;
        $result = true;
    }

} elseif ($this->command == 'sample_action_2') {

    if (isset($_SESSION['foo'][$this->some_id][$this->example_id])) {
        unset($_SESSION['foo'][$this->some_id][$this->example_id]);
        //$_SESSION['foo'][$this->some_id][$this->example_id] = ''; // This works
        $result = true;
    }           

}

print_r($_SESSION['foo']);

Using unset on it doesn't work at all, it still remains. Setting it to a blank value works however.


Solution

  • Finally got a working solution, hopefully this helps someone else:

    $session = Yii::$app->session;
    
    $foo = $session['foo'];
    
    if ($this->command == 'sample_action') {
        $foo[$this->some_id][$this->example_id] = $this->example_id;
    } elseif ($this->command == 'sample_action_2') {
        unset($foo[$this->some_id][$this->example_id]);
    }
    
    $session['foo'] = $foo;