This question is merely for information only.

I was wondering if there is a way to check if a variable is_set and if so check if it is set to null

Based on the PHP type comparison tables doesn't seems like that it is possible.

for example, let's say we have this code:

<?php
$x = null;
if(isset($x) && is_null($x)){
    echo '$x is set to NULL';
}else{
    echo '$x was never initialized';
}
echo "\n";
if(isset($y) && is_null($y)){
    echo '$y is set to NULL';
}else{
    echo '$y was never initialized';
}
echo "\n";
if(is_null($z)){
    echo '$z is set to NULL';
}else{
    echo '$z was never initialized';
}

?>

I would expect the page to show:

$x is set to NULL
$y was never initialized
$z is set to NULL   <it should give an E_NOTICE>

but I am getting

$x was never initialized
$y was never initialized
$z is set to NULL
有帮助吗?

解决方案

$variablename_to_check_against = "varname";
$vars = get_defined_vars();
if (array_key_exists($variablename_to_check_against, $vars) && is_null($$variablename_to_check_against)) {
    echo "$variablename_to_check_against is NULL and exists";
}

get_defined_vars returns the local variable scope (inclusive the superglobals) in key-value pairs.

As array_key_exists returns also true when the variable is NULL, you can use it; then you only have to check if the variable is NULL with is_null.

其他提示

&& means both the conditions in IF clause must be true, as you can see in this Link

$x=null; isset($x) returens false and is_null($x) returns true so we can see that else conditions executes

You're getting correct result because when you assign

$x = null;

it means you're assigning a value to $x and that's why a condition

if(isset($x) && is_null($x)){

is set to false and that's control goes to else part

isset($x) returns true but is_null($x) returns false because value is set (whether it is null) and so && returns false and control goes to else part.

In case of $y

if(isset($y) && is_null($y)){

$y is not declared. So isset($y) is false and therefore control goes to else part.

And why you got message about $z that $z is set to NULL because you didn't have check isset($z) and it's null by default and that's why is_null($z) condition becomes true.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top