Is there a single function that can be created to tell whether a variable is NULL or undefined in PHP? I will pass the variable to the function (by reference if needed) but I won’t know the name of the variable until runtime.
isset() and is_null() do not distinguish between NULL and undefined.
array_key_exists requires you to know the name of the variable as you’re writing your code.
And I haven’t found a way to determine the name of a variable without defining it.
Edit
I’ve also realized that passing a variable by reference automatically defines it.
Elaboration
Through the collection of these answers and comments I’ve determined that the short answer to my question is "No". Thank you for all the input.
Here are some details on why I needed this:
I’ve created a PHP function called LoadQuery() that pulls a particular SQL query from an array of queries and then prepares it for submission to MySQL. Most-importantly I scan the query for variables (like $UserID) that I then replace with their values from the current scope. In creating this function I needed a way to determine if a variable had been declared, and was NULL, empty, or had a value. This is why I may not know the name of the given variable until runtime.
Essentially the answer is no. There is not a single function you can create that will tell whether a runtime variable is null or is undefined. (by ‘runtime variable’ I mean a variable who’s name you don’t yet know at the time of coding. See Elaboration in the question above).
Relevant Observations:
array_key_exists('variable_name', $GLOBALS)as @zzzzBov stated, to see if a variable has been declared, but only if you know the name of the variable at coding time.Possible ‘Dirty’ Solutions
As @Phil (and @zzzzBov) explained you could use a messy trick of capturing error messages that would get thrown when you reference an undeclared variable.
I also considered a method where you: Make note of all the keys in
$GLOBALS, then store a unique value in your target variable (recording it’s original value first for later use). And then search$GLOBALSlooking for that unique value to determine the name of the variable AND (by comparing with your earlier look at$GLOBALS) determine if the variable existed before. But this also seems messy and unreliable.