我试图检测数组元素何时为空,但 is_null
没有完成这项工作。具体来说,我将一些 POST 数据发送到服务器,其中发送的 JavaScript 对象没有值:
$.ajax({
type: "POST",
url: "comms.php",
data: {practice:tab_content}, // array 'tab_content' has not been set
dataType: "script"
});
在服务器 php 代码中,我需要检查“practice”是否有值(如果没有,则在使用 foreach 循环“practice”数组时会出现错误)。
php代码中的print_r($_POST)
显示:
Array
(
[practice] => null
)
这是我的测试程序,它检查 $_POST["practice"] 实际上是什么:
<?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;
?>
Opera 和 Chrome 上的客户端输出是相同的,并且是:
array_key_exists true; is_null false; isset true; empty false; value is 'null'.
知道这是怎么回事吗?谢谢。
编辑 22:10GMT
谢谢大家 - 问题已经解决了。正如你们中的一些人所建议的那样,使用 var_dump 确实提供了必要的信息:
array(1) {
["practice"]=>
string(4) "null"
}
而且,如果我修改 ajax 调用以发送包含“null”的字符串,那么我会得到完全相同的效果。但这很奇怪 - 为什么 XMLHttpRequest 发送一个包含 n-u-l-l 的完全有效的字符串作为空值?这使得发送真正的 n-u-l-l 变得非常困难。考虑到这种困惑,我使用 is_array,正如本杰姆建议的那样。 谢谢 - 喜欢这个网站:)
最佳答案
改为执行 var_dump($_POST),它会显示变量的类型、大小以及内容。
基本上,来自 _GET/_POST/_REQUEST 的任何内容都是字符串。表单中存在但没有数据的字段将显示为空字符串。您的 null 值不是实际的 php“null”,而是一个值为 n-u-l-l 的文字字符串。
给定一个像这样的 php 脚本:
<pre>
<?php
var_dump($_POST);
?>
</pre>
<form method="POST">
<input type="submit" name="submit">
<input type="hidden" name="hidden" value="">
</form>
点击提交将会得到:
array(2) {
["submit"]=>
string(12) "Submit Query"
["hidden"]=>
string(0) ""
}
请注意,“隐藏”字段存在,并且具有 0 长度的字符串作为其值。这意味着:
array_key_exists('hidden', $_POST); -> true
isset($_POST['hidden']); -> true
empty($_POST['hidden']); -> true
is_null($_POST['hidden']); -> false
关于php:空数组元素什么时候不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8362686/