0

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

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The first solution is working, while the seconde one is not. Thanks!
0

Pass the variable by reference :

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

2 Comments

This solution is not working for me, but @Marwelln's one is.
you can use session_unset to unset all the sessions
0

unset it with,

unset($_SESSION);

1 Comment

From php.net: Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.