The isset[]
function does not check if a variable is defined.
It seems you've specifically stated that you're not looking for isset[]
in the question. I don't know why there are so many answers stating that isset[]
is the way to go, or why the accepted answer states that as well.
It's important to realize in programming that null is something. I don't know why it was decided that isset[]
would return false if the value is null.
To check if a
variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars[]
. There is no equivalent to JavaScript's undefined [which is what was shown in the question, no jQuery being used there].
In the following example it will work the same way as JavaScript's undefined check.
$isset = isset[$variable];
var_dump[$isset]; // false
But in this example, it won't work like JavaScript's undefined check.
$variable = null;
$isset = isset[$variable];
var_dump[$isset]; // false
$variable
is being defined as null, but the isset[]
call still fails.
So how do you actually check if a variable is defined? You check the defined variables.
Using get_defined_vars[]
will return an associative array with keys as variable names and values as the variable values. We still can't use isset[get_defined_vars[]['variable']]
here because the key could exist and the value still be null, so we have to use array_key_exists['variable', get_defined_vars[]]
.
$variable = null;
$isset = array_key_exists['variable', get_defined_vars[]];
var_dump[$isset]; // true
$isset = array_key_exists['otherVariable', get_defined_vars[]];
var_dump[$isset]; // false
However, if you're finding that in your code you have to check for whether a variable has been defined or not, then you're likely doing something wrong. This is my
personal belief as to why the core PHP developers left isset[]
to return false when something is null.