Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if var exist before unsetting in PHP?

Tags:

php

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']); ?> 
like image 998
JasonDavis Avatar asked Sep 03 '09 17:09

JasonDavis


People also ask

How do you check if a variable is defined in PHP?

PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

How do you check if a variable is undefined in PHP?

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

What is unset () in PHP?

The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so. The unset() function has no return value.


2 Answers

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

like image 134
João Silva Avatar answered Sep 16 '22 16:09

João Silva


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!

like image 36
Mr. Smith Avatar answered Sep 17 '22 16:09

Mr. Smith