-1

I have 55 session variables and want to unset 54 of them. They all begin with sv

and the one that I want to keep begins with nb

I tried to do this but to no avail. Does anybody have any suggestions?

foreach($_SESSION as $key => $val)
{
    if ($key !== 'nb')
    {
        unset($_SESSION[$key]);
    }
}

I was thinking to use a loop to unset them instead of typing unset(variable) 54 times

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • use ````sub_string```` to check if 'nb' is at the begin of the string. http://stackoverflow.com/questions/2790899/php-how-to-check-if-a-string-starts-with-a-specified-string – Szenis Jun 10 '15 at 10:21

3 Answers3

3

You can use substr() to find the first two letters and exclude 'nb'.

foreach($_SESSION as $key => $val)
{

    if (substr($key,0,2) !== 'nb')
    {

        unset($_SESSION[$key]);

    }

}
Daan
  • 12,099
  • 6
  • 34
  • 51
0

Check that string begins from nb

foreach($_SESSION as $key => $val)
    if (strpos($key,'nb') !== 0) unset($_SESSION[$key]);
splash58
  • 26,043
  • 3
  • 22
  • 34
0

how about this:

foreach($_SESSION as $key => $val)
{
    if (substr($key,0,2) !== 'nb')
    {
        unset($_SESSION[$key]);
    }
}
Mojtaba Rezaeian
  • 8,268
  • 8
  • 31
  • 54