Unset variables after you finished using them [TotD]

Posted by hts | February 10, 2008 .

As I’ve said before, it is good practice to close mysql connections after you have finished working with them.
The same idea applies to variables, especially large arrays holding user data for example. After you used a certain variable and you are sure you don’t need it anymore in your script, simply destroy it to free the memory it used.
The code is dumb-simple:

<?php
$foo
="string";
$file="test.php";
//deletes the value of the variable
unset($foo);
//deletes the file
unset($file);
//etc
?>

Note that unset() destroys the value held by a variable (string, array, file etc.), not the variable itself. For example, if you use isset() after unset(), it would still return true, since the variable exists (is set :) ). Take note of this when writing your scripts, since it can be more of a issue than you would see at a first glance.

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments