Going through the entire $ _SESSION array and removing the null variables

I did some tests with $ _SESSION variables, and many of them were set to NULL, but still exist. I can delete them one by one, but how can I just skip the $ _SESSION array and quickly remove the NULL variables?

+3
source share
7 answers

This will remove the values NULL, but not others empty or FALSE. Easily modified if you also want to get rid of FALSEvals and empty lines, etc.

foreach ($_SESSION as $key=>$var)
{
  if ($var === NULL) unset($_SESSION[$key]);
}
+1
source

You can use array_filterwith a callback function that uses is_null:

$output = array_filter($input, function($val) { return !is_null($val); });
+3
source
$_SESSION = array_filter($_SESSION, 'count');

NULL ( count() 0 NULL), ( ), 0 , PHP:

var, , .

var , 1 . , var NULL, 0 .

0 false , - .

+3

$_SESSION = array_filter($_SESSION);

"" , null.

+1

:

foreach ($_SESSION as $key => $value)
{
    if ($value === NULL)
        unset($_SESSION[$key];
}

P.S. array_filter - "false". , NULL- .

+1
foreach($_SESSION as $key => $value){
   if(empty($value) || is_null($value)){
       unset($_SESSION[$key]);
   }
}
0
source

If you “delete” $_SESSIONitems by setting the value to NULL, you are doing it wrong. To disable an array element, you must use unset on the element $_SESSION.

# Wrong
$_SESSION['foo'] = NULL;

#Good
unset($_SESSION['foo']);
0
source

All Articles