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?
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.
NULL
FALSE
foreach ($_SESSION as $key=>$var) { if ($var === NULL) unset($_SESSION[$key]); }
You can use array_filterwith a callback function that uses is_null:
array_filter
is_null
$output = array_filter($input, function($val) { return !is_null($val); });
$_SESSION = array_filter($_SESSION, 'count');
NULL ( count() 0 NULL), ( ), 0 , PHP:
count()
0
var, , .var , 1 . , var NULL, 0 .
var, , .
var , 1 . , var NULL, 0 .
0 false , - .
$_SESSION = array_filter($_SESSION);
"" , null.
null
:
foreach ($_SESSION as $key => $value) { if ($value === NULL) unset($_SESSION[$key]; }
P.S. array_filter - "false". , NULL- .
foreach($_SESSION as $key => $value){ if(empty($value) || is_null($value)){ unset($_SESSION[$key]); } }
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.
$_SESSION
unset
# Wrong $_SESSION['foo'] = NULL; #Good unset($_SESSION['foo']);