tags:

views:

130

answers:

2

With error reporting on, or even for best practice, when unsetting a variable in PHP, should you check to see if it exist first (in this case it does not always exist) and the unset it, or just unset it?

<?PHP
if (isset($_SESSION['signup_errors'])){
    unset($_SESSION['signup_errors']);
}

// OR

unset($_SESSION['signup_errors']);
?>
+7  A: 

Just unset it, if it doesn't exist, nothing will be done.

JG
I didn't know if it would throw a warning or notice
jasondavis
@jasondavis: what happened when you tried?
SilentGhost
+2  A: 

From the PHP Manual:

In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in

<?php
unset($undefinedVariable);
?>

does not trigger an "Undefined variable" notice. But

<?php
unset($undefinedArray[$undefinedKey]);
?>

triggers two notices, because this code is for unsetting an element of an array; neither $undefinedArray nor $undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!

Mr. Smith