Search code examples
phpsessionunset

Can i use the below to unset several sessions


I have several sessions like this:

$_SESSION['search']['max']
$_SESSION['search']['order']

Currently, I unset each one of them with a separate statement:

if(isset($_SESSION['search']['max']) && $_SESSION['search']['max'] != ''){
        unset($_SESSION['search']['max']);
    }
if(isset($_SESSION['search']['order']) && $_SESSION['search']['order'] != ''){
        unset($_SESSION['search']['order']);
    }

My question is - can I use the below general unset statement instead of having a separate statement for each session:

if(isset($_SESSION['search']) && $_SESSION['search'] != ''){
            unset($_SESSION['search']);
        }

Are there any advantages of declaring each unset statement separately?

Note: I need to unset them all at the same time, meaning I do not need to keep one or more to use again, therefore I believe one statement should do but need to be sure I am not missing out anything.

Thank you all!


Solution

  • I have several sessions like this:

    Nope. You have one session. Those are just variables.

    My question is - can I use the below general unset statement instead of having a separate statement for each session variable:

      if(isset($_SESSION['search']) && $_SESSION['search'] != ''){
            unset($_SESSION['search']);
        }
    

    You can. It's just normal array. And unset($a) is the same as $a = null, so your code is just:

    if(isset($_SESSION['search']) && $_SESSION['search'] != ''){
        $_SESSION['search'] = null;
    }
    

    Meaning that every element of $_SESSION['search'] array will be discarded.

    HOWEVER you are not unsetting session!
    Your session is still live, you just discard some of variables inside the session!

    Are there any advantages of declaring each unset statement separately?

    There is. You have control of which variables stay (like, "I want A and B to stay, but unset C and D"). But if you are like "nah, I'm sure I don't need any of them", then you can just unset them in a bulk and there is nothing wrong with that.