unset()
This function will destroy a variable within the scope you use it.
In a function, an unset variable no longer exists inside of the function but does not affect the variables outside of the function - even if you passed it in by reference, even if you globalized it with the keyword “global”.
Using unset() on a variable in the superglobal array $GLOBALS will affect that variable outside your current scope (as is the nature of the superglobal).
Using this function has a similar effect as setting the variable to NULL. The key difference here is that setting it to NULL means that it is still set. unset() removes it from the list of defined variables.
function unsetter( $one, &$two ) { global $three; unset( $one, $two, $three, $GLOBALS['four'] ); } $one = 'first'; $two = 'second'; $three = 'third'; $four = 'fourth'; $five = 'fifth'; unsetter( $one, $two ); unset( $five ); isset( $one ); // true isset( $two ); // true isset( $three ); // true isset( $four ); // false isset( $five ); // false
See the difference between unset() and setting it to NULL. I’ve put this inside a function so we don’t have all of the variables in the global scope using get_defined_vars().
function unsetter2() { $one = 'this'; $two = 'that'; unset( $one ); $two = NULL; get_defined_vars(); /* array ( 'two' => NULL ) */ }
