Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a variable to NULL in PHP?

I can use isset($var) to check if the variable is not defined or null. (eg. checking if a session variable has been set before)

But after setting a variable, how do I reset it to the default such that isset($var) returns false?

like image 827
Robin Rodricks Avatar asked Dec 06 '09 03:12

Robin Rodricks


People also ask

How do you set a variable to null?

To set the value of a variable is it's equal to null , use the nullish coalescing operator, e.g. myVar = myVar ?? 'new value' . The nullish coalescing operator returns the right-hand side operand if the left-hand side evaluates to null or undefined , otherwise it returns the left-hand side operand.

What is null function in PHP?

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

Is null 0 in PHP?

PHP considers null is equal to zero.

Is null or empty PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .


2 Answers

Use unset($var);

like image 70
nacmartin Avatar answered Sep 20 '22 22:09

nacmartin


As nacmartin said, unset will "undefine" a variable. You could also set the variable to null, however this is how the two approaches differ:

$x = 3; $y = 4; isset($x);  // true; isset($y);  // true;  $x = null; unset($y); isset($x);  // false isset($y);  // false  echo $x;  // null echo $y;  // PHP Notice (y not defined) 
like image 28
nickf Avatar answered Sep 20 '22 22:09

nickf