【问题标题】:Undefined offset notice in loop循环中未定义的偏移量通知
【发布时间】:2013-03-04 21:59:05
【问题描述】:

我正在使用脚本来创建额外的表单行。 它为某些文本字段循环 $i 数字 当我运行这个脚本时,偏移量是未定义的,因为它不存在。 我需要使用 if(isset()) 函数,但我不确定如何将它放在代码中。 有人可以帮忙吗?

for ($i=0; $i<100; $i++) {

    if ($text['length'][$i] == "") $text['length'][$i] = "0";
    if ($text['bredth'][$i] == "") $text['bredth'][$i] = "0";
    if ($text['height'][$i] == "") $text['height'][$i] = "0";
    if ($text['weight'][$i] == "") $text['weight'][$i] = "0.00";

所有以'if'开头的行都显示通知:

注意:未定义的偏移量:C:\xampp\htdocs\newparcelscript.php 第 41 行中的 1

已解决 事实上,我根本不需要和“if”语句,因为行的创建和值的设置是一起运行的。

for ($i=0; $i<100; $i++) {

   $text['length'][$i] = "0";
   $text['breadth'][$i] = "0";
   $text['height'][$i] = "0";
   $text['weight'][$i] = "0.00";

【问题讨论】:

  • 我建议试试 $text[$i]['weight']
  • 很高兴我能帮上忙 ;)

标签: php loops undefined offset


【解决方案1】:

我认为测试empty() 就是您要在这里寻找的内容。

for($i = 0; $i < 100; $i++)
{
    if(empty($text['length'][$i]) === TRUE) $text['length'][$i] = 0;
    ...
    ...
}

【讨论】:

    【解决方案2】:

    根据您在此处尝试执行的操作,我建议您使用以下其中一种 isset/empty 组合

    if (isset($text['length'][$i]) == false or empty($text['length'][$i]) == true)
    
    if (isset($text['length'][$i]) == true and empty($text['length'][$i]) == true)
    

    错误很可能来自对不存在的索引进行测试:if($text['length'][$i] == "")

    【讨论】:

    • 已解决,我正在创建这些行,但是用于创建和设置值的代码是同时运行的,所以实际上我根本不需要'if'语句
    【解决方案3】:

    对于这种情况,如果您需要为未定义的字段插入值,请使用empty()

    empty() 如果值为空字符串,则返回 TRUE,而 !isset() 将返回 FALSE。
    对此有很多疑问,例如look here

    类似这样的:

    for ($i=0; $i<100; $i++) {
        if (empty($text['length'][$i])) $text['length'][$i] = "0";
        if (empty($text['bredth'][$i])) $text['bredth'][$i] = "0";
        if (empty($text['height'][$i])) $text['height'][$i] = "0";
        if (empty($text['weight'][$i])) $text['weight'][$i] = "0.00";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多