Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for NULL value in a variable that may not be set

Tags:

php

Considering that:

  • The isset() construct returns TRUE if a variable is set and not NULL
  • The is_null() function throws a warning if the variable is not set

Is there a way to test whether a variable exists, no matter it's NULL or not, without using the @ operator to suppress the notice?


EDIT

Together with your first replies, I've been thinking about this and I'm getting the conclusion that inspecting get_defined_vars() is the only way to distinguish between a variable set to NULL and an unset variable. PHP seems to make little distinctions:

<?php

$exists_and_is_null = NULL;

// All these are TRUE

@var_dump(is_null($exists_and_is_null));
@var_dump(is_null($does_not_exist));

@var_dump($exists_and_is_null===NULL);
@var_dump($does_not_exist===NULL);

@var_dump(gettype($exists_and_is_null)=='NULL');
@var_dump(gettype($does_not_exist)=='NULL');

?>
like image 968
Álvaro González Avatar asked Feb 17 '10 19:02

Álvaro González


1 Answers

$result = array_key_exists('varname', get_defined_vars());
like image 137
thetaiko Avatar answered Sep 28 '22 16:09

thetaiko