Reputation: 14614
I want to use such code:
$arr=array('a'=>$a);
but $a
is not defined, so I get error. But if I write this code before
if (!isset($a))
$a=null;
all works. Why? In the beginning $a
is not defined , so $a=null
. or underfined!=NULL
?
Upvotes: 1
Views: 100
Reputation: 14909
As you already discovered undefined is different from null.
Undefined means that the name $a in not yet into the scope of your function/code.
$a=null
is a (no)value assigned to a variable.
By the way you should get a Notice, not an error as using undefined variables as right-values php warns you about a probable typo and proceed with the script execution.
As a rule of thumb, if you address an undefined variable on the left of the assignment (=) simbol (a left-value name) then php create a new variables name and bind it into the current scope, if the reference is on the right (are you using the value contained instead than the variable itself) php warns you and keep going. You can change this behaviour by the error_reporting function.
Upvotes: 3
Reputation: 5320
When you write
array("a"=>$a)
it means that you want the key "a" refers to a variable reference named $a which does not exist in the first place thus you are getting an error; but when you add
$a=null;
before hand, although you are setting $a to null but actually you are creating a variable reference named $a that's known by PHP so there will be no errors.
Upvotes: 6
Reputation: 106920
Yes, in truth undefined
!= null
, although the difference is only in the eyes of PHP when it decides whether to throw an error or not. Otherwise it's the same thing.
Upvotes: 3
Reputation: 54022
see the manual of isset
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Upvotes: -1