What is difference between assigning a variable to NULL and unset?

Difference between assigning a variable to NULL and unset.

[php]<?php $var = NULL; ?>[/php]

A variable is considered to be NULL if

It has been assigned the constant NULL.
It has not been set to any value yet.
It has been unset().

Setting a variable to NULL means assigns the value NULL to the variable exactly as the variable is set to a value and value is the special value NULL.
That means memory needs to be allocated where the NULL value is stored and an entry into the symbol table needs to be made.
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.


[php]<?php unset($var); ?>[/php]


unset() destroys the specified variables.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

unset() means the variable is no longer set, it doesn’t have a value and basically the variable doesn’t exist anymore.
Unsetting a variable removes the entry for the variable from the symbol table.



$var = NULL;
var_dump($var); -> NULL

var_dump($var); -> NOTICE: Undefined variable var on line 21



Casting to NULL
Casting a variable to NULL using (unset) $var will not remove the variable. It only return a NULL value.


unset does not force immediate memory freeing but leaves it for the Garbage Collector.
$var = NULL; however forces immediate memory release.


So,It totally depends on the situation you have, both are good to use,but setting the value to NULL is faster.


One thought on “What is difference between assigning a variable to NULL and unset?”

  1. I am really delighted to read this website posts which consists of tons of helpful facts, thanks for providing these information.

Comments are closed.