Forum Moderators: coopster
//from php.net site
$a = array ('test' => 1, 'hello' => NULL);
var_dump(isset($a['test'])); // TRUE
var_dump(isset($a['foo'])); // FALSE
var_dump(isset($a['hello'])); // FALSE
//my testing
if(isset($_POST['submitted'])) {
print "submitted is set";
}
<form action="<?=$PHP_SELF;?>" method="post">
<input type="hidden" name="submitted" value=NULL>
<p><input name="submit" type="submit" value="submit"></p>
</form>
Notice that I explicitly set "submitted" to NULL
I used the following code to print out all my $_POST variables to make sure that "submitted" is indeed set to NULL
foreach($_POST as $key => $value)
print $key."=>".$value;
This prints out submitted=>NULL, submit=>submit so now I know for sure that "submitted" is set to NULL and according to the php.net site, using isset on a variable that is explicitly set to NULL will be false. But why is if(isset($_POST['submitted'])) return true and prints "submitted is set"?
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
However, you are not posting the php constant NULL, you are posting a string with the value of NULL.
You can dump your $_POST to see this. var_dump($_POST) on your form outputs:
array(2) {
["submitted"]=>
string(4) "NULL"
["submit"]=>
string(6) "submit"
} the PHP constant NULL is not a string, which you can see from this test:
php > $array = array(NULL, 'NULL');
php > var_dump($array);
array(2) {
[0]=>
NULL
[1]=>
string(4) "NULL"
}
php >
That would be my recommendation as well for checking if a POSTed variable has a value. Though there are a few cases where you will also need to use isset(), for example checkboxes which are not posted if they are not checked.
Some people also use isset() for other reasons on POST data as well. One example would be that it is good practice to use isset() if you are not sure if a variable is set or not, which in the case of POST data, it is subject to all kinds of manipulation, and you can't be sure of anything. So if you're doing that, you probably want to do a double check, "if is set and not empty".
If you submit something like
<input type="hidden" name="number" value=34>
$_POST['number'] will have the string type
$is_int = is_int($_POST['number']); //$is_int set FALSE
$is_string = is_string($_POST['number']); //$is_string set TRUE
$is_numeric = is_numeric($_POST['number']); //$is_numeric set TRUE