Search code examples
phparrayssessionforeachunset

PHP - Unset $_SESSION variables using foreach


Is it possible to unset $_SESSION variables using a foreach cycle? This is an example.

<?php
session_start();
$_SESSION['one'] = 'one';
$_SESSION['two'] = 'two';
$_SESSION['three'] = 'three';
print_r($_SESSION);
foreach($_SESSION as $value) {
    unset($value);
}
session_destroy();
print_r($_SESSION);
?>

I think that this script should work but it's not working for me. It gives me this output, without unsetting the variables :

Array ( [one] => one [two] => two [three] => three )
Array ( [one] => one [two] => two [three] => three )

Maybe it's a problem related to superglobal arrays. I can anyway unset the variables using their key :

unset($_SESSION['one']);

Solution

  • You must get the key and unset $_SESSION[$key] or pass your variable by reference (not sure if you can unset a reference).

    foreach($_SESSION as $key => $value) {
        unset($_SESSION[$key]);
    }
    
    foreach($_SESSION as &$value) {
        unset($value);
    }