DamiToma
DamiToma

Reputation: 1106

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

Upvotes: 0

Views: 1419

Answers (3)

LF-DevJourney
LF-DevJourney

Reputation: 28529

unset it with,

unset($_SESSION);

Upvotes: 0

Bara&#39; ayyash
Bara&#39; ayyash

Reputation: 1935

Pass the variable by reference :

foreach($_SESSION as &$value) {
    // edit $value
}

Upvotes: 0

Marwelln
Marwelln

Reputation: 29413

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

Upvotes: 2

Related Questions