0

I got the following function:

public function stopWatcherSession($sessionID) {
    if(array_key_exists($sessionID, $_SESSION[self::WATCHER_SESSION_KEY])) {
        foreach ($_SESSION[self::WATCHER_SESSION_KEY][$sessionID]['names'] as $v) {
            $ptype = $this->paramTypeFromName($v);
            unset($_SESSION[self::SESSION_KEY][$ptype][$v]); //does not work, sets entry to null
        }
        unset($_SESSION[self::WATCHER_SESSION_KEY][$sessionID]); //does not work, sets entry to null
    }
}

As the comments say, the array entry does not get unset, the array_key_exists()-function still returns true, and if you var_dump($_SESSION) you can see, that $_SESSION[self::WATCHER_SESSION_KEY][$sessionID] is null.

How can I unset the variable, so that also the key in the array gets removed?

Things i tried, that did not work:

// v1 (tried also for `$_SESSION[self::WATCHER_SESSION_KEY][$sessionID]` )
$tmp = $_SESSION[self::SESSION_KEY][$ptype];
unset($tmp[$v]);
$_SESSION[self::SESSION_KEY][$ptype] = $tmp;

//v2
unset($_SESSION[self::WATCHER_SESSION_KEY][$sessionID]);
session_write_close();
session_start();

//v3 => v1 & v2 combined
$tmp = $_SESSION[self::SESSION_KEY][$ptype];
unset($tmp[$v]);
$_SESSION[self::SESSION_KEY][$ptype] = $tmp;
session_write_close();
session_start();

I could add a crappy hack all over the code to check whether it's null, but then »empty« values must be changed to something else (like a predefined const, but thats a nasty workaround and leads to confusion for other devs!)

Anyone got some ideas?

beatjunky99
  • 149
  • 11
  • Empty vals can remain in array and for null checking use `isset` – u_mulder Jul 07 '15 at 08:15
  • If the standard value for 'submitted, but no value entered' is `null` and not in the array is 'not submitted', then it's not a good thing to have still the key there floating around with a `null`-value. Unsetting should solve this... – beatjunky99 Jul 07 '15 at 10:26

1 Answers1

2

Got it working:

unset($GLOBALS['_SESSION'][self::WATCHER_SESSION_KEY][$sessionID]); does the job.

http://php.net/manual/en/function.unset.php says:

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. […] To unset() a global variable inside of a function, then use the $GLOBALS array to do so

Seems like a classical »PHP behaviour is undefined in some cases«-example.

beatjunky99
  • 149
  • 11