How to determine if a variable is null or undefined in php

Is there a single function that can be created to indicate if a variable is NULL or undefined in PHP? I will pass the variable to the function (by reference, if necessary), but I will not know the variable name 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 when writing your code.
And I did not find a way to determine the name of a variable without defining it.

Edit

I also realized that passing a variable by reference automatically determines it.

Development

As a result of collecting these answers and comments, I decided that the short answer to my question is β€œNo.” Thanks for all the input.

Here are some details about why I need this:

I created a PHP function called LoadQuery() that pulls a specific SQL query from an array of queries and then prepares it for sending to MySQL. Most importantly, I am looking at a query for variables (e.g. $UserID ), which then replace them with values ​​from the current scope. When creating this function, I need a way to determine if a variable was specified and was NULL, empty, or had a value. This is why I may not know the name of this variable until runtime.

+4
source share
7 answers

In fact, the answer is no. There is not one function that you can create that will determine if the runtime variable is zero or equal to undefined. (by the variable "runtime" I mean a variable whose name you still do not know during coding. See Development in the question above).

Relevant observations:

  • It is not possible to get the name of a variable at run time without giving it a value and therefore declaring it.
  • If you pass a variable by reference, not by value, you automatically declare it. So then in the function you cannot go back and determine if it was declared before you passed it.
  • You can use array_key_exists('variable_name', $GLOBALS) as indicated by @zzzzBov to find out if a variable is declared, but only if you know the name of the variable during encoding.

Possible dirty solutions

  • As @Phil (and @zzzzBov) explained, you can use a dirty trick to capture error messages that will be issued when referencing an undeclared variable.

  • I also looked at a method in which you: pay attention to all the keys in $GLOBALS , then store the unique value in your target variable (first writing down the original value for later use). And then searching for $GLOBALS , which searches for this unique value to determine the name of the AND variable (comparing with your previous view of $GLOBALS ), determines if this variable previously existed. But it also seems messy and unreliable.

+2
source

In PHP, usually variables that have not been set or have been canceled are considered null . The null value is "no value". There is a great difference between β€œno value” and a value left blank. For example, if the user submitted a form with foo=&bar=baz , $_GET['foo'] set to the empty string "" , which is clearly different from null , which will be the value for any key except 'foo' and 'bar' .

To get it all said, you can find out if a variable or unset , although they will always be evaluated as true with is_null ( is_null is a negative isset value with the exception that it will notify if the value has never been set).

One way is if you have a variable in an array of some type:

 echo array_key_exists( $variableName, $theArray ) ? 'variable was set, possibly to null' : 'variable was never set'; 

If you need to check a global variable, use the $GLOBALS array:

 echo array_key_exists( $variableName, $GLOBALS ) ? 'variable exists in global scope' : 'this global variable doesn\'t exist'; 

The alternative method that I came up with to determine whether the variable was set is a little more involved and really unnecessary, unless it means what you need to have (in which you should be able to build it without much difficulty).

It relies on the fact that is_null triggers a notification when a variable has not been set. Add an error handler that converts errors to Exceptions , and use the try...catch... to catch the exception that threw and set the flag in the catch statement. Once the catch executes your code that will use this function.

This is a dirty nasty hack if you ask me and are completely unnecessary, since null should be considered as an unset variable.

+2
source

You cannot wrap this logic in a function or method, since any variable defined in the function signature will be implicitly "set". Try something like this (contains a smell of code)

 function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } error_reporting(E_ALL); set_error_handler("exception_error_handler"); try { if (null === $var) { // null your variable is, hmmm } } catch (ErrorException $e) { // variable is undefined } 
+1
source

You can get an array of specific variables in the current area with:

 get_defined_vars(); 
+1
source

This only works with globally defined variables. Due to visibility, this will not work with local variables in functions or with class properties, but, of course, this is only one line, so you can just copy it into a function.

 function isNullOrUndefined($variable_name) { global $$variable_name; if (!isset($$variable_name) || is_null($$variable_name)) { return true; } return false; } $foo = "foo"; $bar = null; isNullOrUndefined("foo") //false isNullOrUndefined("bar") //true isNullOrUndefined("baz") //true 
0
source

how about this?

 try { $undefined_var } catch (Exception $ex) { $is_undefined = true; } if(empty($is_undefined)){ ... } 
0
source

If your version of PHP is greater than or equal to 5.2, the function below can do this:

 $a = NULL; // comment this line and you will see an indication of 'Undefined' $b = $c; // generates an error that must be neutralized, before testing $a variable /* possible intermediate code */ @trigger_error('do not consider this notice'); // neutralize last error associated with $c (push it down in the stack) $status = @check_last_error_info( $a ); // new error associated with $a echo $status; function check_last_error_info() { $last_error = error_get_last(); // capture new error if ( $last_error['type'] == 8 && strpos($last_error['message'], 'Undefined variable:') === 0 ) { return 'Undefined variable'; } else { return 'Defined variable'; } } 

Note that you MUST have a trigger_error operation before calling the function. Otherwise, you can fix the error generated by other parts of your code.

0
source

All Articles