-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
  • 20,667
  • 5
  • 43
  • 53
Devin Gray
  • 1,933
  • 4
  • 21
  • 42
  • 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
  • 11,690
  • 6
  • 30
  • 49
0

Check that string begins from nb

foreach($_SESSION as $key => $val)
    if (strpos($key,'nb') !== 0) unset($_SESSION[$key]);
splash58
  • 25,715
  • 3
  • 20
  • 32
0

how about this:

foreach($_SESSION as $key => $val)
{
    if (substr($key,0,2) !== 'nb')
    {
        unset($_SESSION[$key]);
    }
}
Mojtaba Rezaeian
  • 7,315
  • 7
  • 27
  • 50