开发者

Going through my entire $_SESSION array and removing null variables

开发者 https://www.devze.com 2023-03-03 09:04 出处:网络
I\'ve been doing some tests with $_SESSION variables and that left a lot of them set to NULL, but still existing. I can remove them one-by-one, but how can I just loop through the $_SESSION array and

I've been doing some tests with $_SESSION variables and that left a lot of them set to NULL, but still existing. I can remove them one-by-one, but how can I just loop through the $_SESSION array and remove NULL variables quickly开发者_开发技巧?


You can use array_filter with a callback function that uses is_null:

$output = array_filter($input, function($val) { return !is_null($val); });


$_SESSION = array_filter($_SESSION, 'count');

Will have the effect of removing all NULL values (since count() returns 0 for NULL) and also any countable (either an array or an object) that has 0 elements, from the PHP manual:

Returns the number of elements in var, which is typically an array, since anything else will have one element.

If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Since 0 evaluates to false in a boolean context there is no need to implement any custom function.


This will remove NULL values, but not other empty or FALSE. Easily modified if you also want rid of FALSE vals and empty strings, etc.

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


$_SESSION = array_filter($_SESSION);

This will remove any "falsy" values from the session array, including null.


That should do it:

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

P.S. array_filter will remove anything equal to "false". You should provide your own callback function or use this example if you need to remove only NULL-values and keep empty strings or zeros.


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


If you are "deleting" $_SESSION elements by setting value to NULL, you are doing it wrong. To unset array element you should use unset on $_SESSION element.

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

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

精彩评论

暂无评论...
验证码 换一张
取 消