【问题标题】:PHP Undefined offset: 0 with issetPHP 未定义偏移量:0 with isset
【发布时间】:2016-10-12 10:25:48
【问题描述】:

我试图了解 PHP 在使用 isset() 函数时抛出未定义的偏移错误是否正确。 数据来自一个雄辩的集合。

$interest->vehicles

当集合为空时会出现问题。 下面的代码在 3 种不同的设置(Mac+Mamp PRO、Windows+Xampp、Mac+Mamp)上进行了测试,在前两种设置中抛出未定义的偏移量,但在我的第三个设置中没有(Mac+Mamp) 所有测试场景均使用 PHP 7 完成并显示错误 On。

isset($interest->vehicles[0]['make'])

我理解为什么错误可能发生在其他设置上,因为我尝试使用 isset 的偏移量不存在,但我不明白的是为什么我在使用 isset 时在我的设置上看不到错误.

我还尝试在我的机器上重新安装 Mamp,升级到 Sierra OS,重新启动我的笔记本电脑,更改 php.ini 设置以始终显示所有错误。

ErrorException in Collection.php line 1043:
Undefined offset: 0 (View: /Users/efood-leo/Sites/cardealer/resources/views/panel/interest/form.blade.php) (View: /Users/efood-leo/Sites/cardealer/resources/views/panel/interest/form.blade.php)

这是我所说的错误,只有当我尝试检索时才会发生

$interest->vehicles[0]['make']

当车辆[0]不存在时。

如果我这样做:

isset($interest->vehicles[0]['make'])

然后我的设置没有错误,其他 2 位开发人员报告错误仍然发生在 isset。

【问题讨论】:

  • if(isset($interest)) {if(count($interest->vehicles) > 0) { var_dump($interest->vehicles; ) } }
  • Cannot reproduce. 请提供$interest的确切错误消息和实现。
  • 尝试只使用if ($interest->vehicles) 评估结果而不使用isset
  • 我不是在尝试解决问题,而是在尝试在我的设置中重现该错误,但不会产生错误。我更新了错误消息
  • @deceze 集合是一个空数组3v4l.org/ahjZ2

标签: php undefined offset isset


【解决方案1】:

试试这个代码。

Isset() 函数以某种方式返回 true,所以没有 isset 它可以工作

$interest = (object)['vehicles' => []];

echo $interest->vehicles[0]['make'];

阅读有关 isset() 的更多信息: http://php.net/manual/en/function.isset.php

【讨论】:

  • 我试过了,它似乎是正确的!仍然无法弄清楚为什么我的同事会看到 isset 出现未定义的偏移错误。 3v4l.org/aOZOd
  • 希望你的机器运行相同版本的 PHP。不知何故 isset() 可能认为错误是一个值,因为它旨在检查传递的参数是否存在,因此它不返回任何内容。小心你如何使用isset()。 If 语句对于基本评估很有用。
  • 从 isset 文档中清楚地表明 isset 将在不存在的更深的数组值上返回 false: var_dump(isset($a['cake']['a']['b' ])); // 错误
  • 数组键与值不同......您正在使用无效键访问数组。如果键存在且值为 null 或为空,Isset 将返回 false
猜你喜欢
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2014-06-25
相关资源
最近更新 更多