I'm trying to detect when an array element is null, but is_null isn't doing the job. In detail, I'm sending some POST data to a server, where the JavaScript object sent has no value:
$.ajax({
type: "POST",
url: "comms.php",
data: {practice:tab_content}, // array 'tab_content' has not been set
dataType: "script"
});
In the server php code, I need to check whether 'practice' has a value (if it doesn't, I get an error when using foreach to cycle through the 'practice' array).
print_r($_POST) in the php code shows:
Array
(
[practice] => null
)
Here's my test program which checks what $_POST["practice"] actually is:
<?php
$params = "";
if(array_key_exists("practice", $_POST))
$params .= "array_key_exists true;";
else
$params .= "array_key_exists false;";
if(is_null($_POST["practice"]))
$params .= " is_null true;";
else
$params .= " is_null false;";
if(isset($_POST["practice"]))
$params .= " isset true;";
else
$params .= " isset false;";
if(empty($_POST["practice"]))
$params .= " empty true;";
else
$params .= " empty false;";
$params .= " value is '" . $_POST["practice"] . "'.";
$output = "document.getElementById(\"demo\").innerHTML=\"";
$output .= $params;
$output .= "\";\n";
echo $output;
?>
The client output is identical on Opera and Chrome, and is:
array_key_exists true; is_null false; isset true; empty false; value is 'null'.
Any idea what's going on here? Thanks.
EDIT 22:10GMT
Thanks everybody - that's fixed it. Using var_dump did give the necessary information, as a couple of you suggested:
array(1) {
["practice"]=>
string(4) "null"
}
And, if I modified the ajax call to send a string containing "null", then I got exactly the same effect. This is pretty strange, though - why does XMLHttpRequest send through a completely valid string containing n-u-l-l for an empty value? That makes it pretty difficult to send through a real n-u-l-l. Given this confusion, I'm using is_array, as benjam suggested. Thanks - love this site :)
$foo = NULL; print "-$foo-";prints--, not-null-.var_dumpinstead ofprint_rto obtain more information about the value in question.application/x-www-form-urlencoded, which has no datatypes--all parameter names and values are strings. If you want to send a real null, you need to send JSON or some other format that has a concept of null.