【问题标题】:php contradictions with $_POSTphp 与 $_POST 的矛盾
【发布时间】:2016-10-17 23:44:02
【问题描述】:

我有这个程序:

if (!isset($_POST['foo'])) doSomeThing1();
else {
    if (!array_key_exists('foo',$_POST)) doSomeThing2();
    else doSomeThing3();
}

但是...程序流程转到 3d 案例,失败并出现错误:undefined index 'foo' (in file.php, line xxx)

你能解释一下,为什么? 为什么array_key_exists 返回true(将脚本带到 3d 案例)但随后它是“未定义索引”?

【问题讨论】:

  • 您是否尝试过使用var_dump($_POST) 查看您的数据?这也可以帮助我们调试。还有 - file.php:xxx 中有什么?抛出错误的代码可能与调试错误有关,你不觉得吗?
  • 请先print您的帖子值,即使您可以使用var_dump() 更了解究竟是什么数据以及为什么它不符合任何条件。
  • doSomeThing3() 暗示了什么?
  • 当 $_POST 中有 'foo' 键时,请告诉我们您的期望;当 $_POST 等中没有 'foo' 键时
  • 谢谢,祝你有美好的一天

标签: php array-key-exists


【解决方案1】:
if (!isset($_POST['foo'])) doSomeThing1();
else {
    if (!array_key_exists('foo',$_POST)) doSomeThing2();
    else doSomeThing3();
}

根据这段代码,它是如何工作的......

!isset($_POST['foo']) ==> 返回true 并在$_POST 数组中没有'foo' 键时执行dosomeThing1()

如果$_POST 没有任何密钥,它正在检查!array_key_exists('foo',$_POST)

array_key_exists('foo', $_POST) 检查'foo' 键是否存在于$_POST 数组中。 array_key_exists('foo', $_POST)isset($_POST['foo']) 相同,所以当$_POST 数组中没有'foo' 键时,它总是执行doSomeThing3()

希望这个解释有所帮助。

【讨论】:

    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2017-11-06
    • 2016-02-21
    相关资源
    最近更新 更多