Open In App

Which one is better (unset() or $var = null) to free memory in PHP ?

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)

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
  
    // Declare a variable and set
    // to some string
    $a = "hello geeks";
    echo "Before unset : $a";
          
    // Unset this variable
    unset($a);
    echo "<br>";
  
    // Display the variable
    echo "After unset : $a";
?>


 

Output:

Before unset : hello geeks
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
  
    // Declare a variable and
    // set to string
    $a = "Hello geeks";
    echo "Before null : $a";
          
    // Assign null to this variable
    $a = null;
    echo "<br>";
  
    // Display result
    echo "After null : $a";
?>

Output:

Before null : Hello geeks
After null :

Which one is better?

unset() function:

null variable:

Conclusion: NULL is better if the memory needed is less for a variable.


Article Tags :