In this article, we will discuss freeing the memory with unset() and using NULL value to any variable.
unset(): The unset() function is an inbuilt function in PHP that is used to unset a specified variable. The unset() function just destroys or removes the variable from the symbol table. After the unset() applied on a variable, it’s marked for PHP garbage collection.
Syntax:
unset($variable)
- $variable which is unset
Example: The following example demonstrates the unset() function. In the following example, the $a memory is removed from the variable stack, the $a does not exist anymore after the unset action.
PHP
<?php       // Declare a variable and set     // to some string     $a = "hello neveropen" ;     echo "Before unset : $a" ;               // Unset this variable     unset( $a );     echo "<br>" ;       // Display the variable     echo "After unset : $a" ; ?> |
Â
Output:
Before unset : hello neveropen After unset :
null: null is used to empty the variable. We can create a null variable by simply assigning it to null. The memory is not freed, but NULL data is re-written or re-assigned on that particular variable.
Syntax:
$variable = null;
Example:
PHP
<?php       // Declare a variable and     // set to string     $a = "Hello neveropen" ;     echo "Before null : $a" ;               // Assign null to this variable     $a = null;     echo "<br>" ;       // Display result     echo "After null : $a" ; ?> |
Output:
Before null : Hello neveropen After null :
Which one is better?
unset() function:
- unset() does not force immediate memory freeing, and it is used to free variable usage.
- PHP garbage collector cleans up the unset variables.
- CPU cycles are not wasted
- It takes time to free memory
null variable:
- null variable immediately frees the memory.
- CPU cycles are wasted and it takes longer execution time.
- It speedily frees the memory.
Conclusion: NULL is better if the memory needed is less for a variable.