Php test if variable is undefined

PHP — determine whether the variable is undefined or NULL

I want to write a function to set an undefined variable to the default value that it can prevent warning of an undefined variable. If I use the isset() function to determine the input variable, the variable will change to the default value if a variable is equal to NULL . Could any method implement this? Example:

function init_variable($input, $default = '123') < . return $inited_variable; >$variable1 = init_variable($_POST['ABC']); $variable2 = init_variable($_POST['DEF'], 'DEF'); 

PHP has three functions that should help you: isset() , empty() and is_null() . You should read the PHP doc for more info.

Do you mean you want your init_variable function to gracefully handle the case when $_POST[‘ABC’] is not defined?

note: is_null() will return true on a variable that hasn’t been defined; there isn’t a default type for variables — but undefined variables are null .

5 Answers 5

There is a much more elegant way since PHP 7 called Null coalescing operator:

$variable1 = $_POST['ABC'] ?? 'DEFAULT VALUE' 

If you just want to set defaults:

$var = isset($_POST['ABC'])) ? $_POST['ABC'] : false; 
$var = false; if(isset($_POST['ABC'])) $var = $_POST['ABC']; 

If $_POST[‘ABC’] does not exist, then PHP will raise an error at exactly this point:

You cannot prevent this error from happening from within init_variable . Your function will only receive the end result of trying to access an undefined variable/index, it cannot prevent that from happening.

What you want is simply the null coalescing operator:

$variable2 = isset($_POST['ABC']) ? $_POST['ABC'] : '123'; 

if the checking isset($_POST[‘ABC’]) ? $_POST[‘ABC’] : ‘123’; in function is doing at the first time, it is workable too as i teseted. however, the function cannot determine between NULL and undefined.

You can determine whether an array_key_exists specifically, which allows you to distinguish between undefined and null . But there is indeed no way to distinguish between an undefined variable and a variable holding null . Specifically for $_POST : POSTed data can never be null , at worst it’s an empty string, so that shouldn’t really be any concern.

You could include this in your project

if ( ! function_exists('array_get')) < /** * Get an item from an array using "dot" notation. * * @param array $array * @param string $key * @param mixed $default * @return mixed */ function array_get($array, $key, $default = null) < if (is_null($key)) return $array; if (isset($array[$key])) return $array[$key]; foreach (explode('.', $key) as $segment) < if ( ! is_array($array) || ! array_key_exists($segment, $array)) < return $default; >$array = $array[$segment]; > return $array; > > 

What it does is split the string by dot ( . ) and then try to fetch the elmenents that in that array. so if you’d do array_get($array, ‘foo’); it would be as if you’d type $array[‘foo’]. But if the variable is set in the array, it will return it’s value. null is a valid value, but not one you’re likely to find in a $_POST array.

But if you also wish to filter out the null values I do recommend using a manual check instead of a catch all. Sometimes you want that null. But if you need a function for it I suggest modifying the above function to

if ( ! function_exists('array_get')) < /** * Get an item from an array using "dot" notation. * * @param array $array * @param string $key * @param mixed $default * @return mixed */ function array_get($array, $key, $default = null) < if (is_null($key)) return $array; if (isset($array[$key])) < $value = $array[$key]; /** * Here is the null check. You can also add empty checks and other checks. */ if(is_null($value)) < return $default; >return $value > foreach (explode('.', $key) as $segment) < if ( ! is_array($array) || ! array_key_exists($segment, $array)) < return $default; >$array = $array[$segment]; > return $array; > > 
array_get($_POST,'abc','some default value'); 

That way you don’t have to worry if it’s intantiated or not.

Added bonus is, if you have nested arrays, this makes it easy to access them without having to worry if the lower arrays are initiated or not.

$arr = ['foo' => ['bar' => ['baz' => 'Hello world']]]; array_get($arr, 'foo.bar.baz', 'The world has ended'); array_get($arr, 'foo.bar.ouch', 'The world has ended'); 

Источник

How to tell whether a variable is null or undefined in php

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

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.

One could play extremely dirty tricks with get_last_error and the like, but that would just be a theoretical exercise, not something I’d ever like to see in code. I will say that it smells like a very weird thing to do, and possibly this can be better handled on another level / with another design. Could you give us some example how you would use this code?

@Phil: I was thinking even dirtier, with get_last_error mashed with debug_backtrace . But still, this should not be needed. There’s a design flaw here, unless it’s a purely academic question, and we should explore that

8 Answers 8

$v1 = null; echo (isset($v1) ? '$v1 set' : '$v1 not set') . PHP_EOL; echo (is_null($v1) ? '$v1 null' : '$v1 not null') . PHP_EOL; echo (empty($v1) ? '$v1 empty' : '$v1 not empty') . PHP_EOL; echo (array_key_exists('v1', get_defined_vars()) ? '$v1 defined' : '$v1 not defined') . PHP_EOL; echo PHP_EOL; echo (isset($v2) ? '$v2 set' : '$v2 not set') . PHP_EOL; echo (@is_null($v2) ? '$v2 null' : '$v2 not null') . PHP_EOL; echo (empty($v2) ? '$v2 empty' : '$v2 not empty') . PHP_EOL; echo (array_key_exists('v2', get_defined_vars()) ? '$v2 defined' : '$v2 not defined') . PHP_EOL; 
$v1 not set $v1 null $v1 empty $v1 defined $v2 not set $v2 null $v2 empty $v2 not defined 

we can use array_key_exists(. get_defined_vars()) and is_null(. ) to detect both situations

You can’t wrap this kind of logic in a function or method as any variable defined in a function signature will be implicitly «set». Try something like this (contains code smell)

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 >

In PHP typically variables that have not been set or that have been unset are considered null . The meaning of null is «no value». There is a distinct difference between «no value» and a value left blank. For instance, if a user submitted a form with foo=&bar=baz , $_GET[‘foo’] is set to the value of empty string «» , which is distinctly different from null which would be the value for any key other than ‘foo’ and ‘bar’ .

That all being said, you can find out if a variable was never set or unset , although they will always evaluate to true with is_null ( is_null is the negative of isset with the exception that it will throw notices if the value was never set).

One way is if you have the variable in an array of some sort:

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 I’ve come up with for figuring out whether the variable was set is a bit more involved, and really unnecessary unless this is a feature that you absolutely have to have (in which case you should be able to build it without too much difficulty).

It relies on the fact that is_null triggers a notice when a variable hasn’t been set. Add an error handler that converts errors into Exceptions , and use a try. catch. block to catch the exception that’s thrown and set a flag in the catch statement. Just after the catch block execute your code that relies on this feature.

It’s a dirty-nasty-hack if you ask me, and completely unnecessary, as null should be considered the same as an unset variable.

Источник

Читайте также:  Python generate unique number
Оцените статью