【问题标题】:for loop not processing first element of array [duplicate]for循环不处理数组的第一个元素[重复]
【发布时间】:2023-03-11 00:40:02
【问题描述】:

我对我的代码中的一个问题感到困惑,希望其他人可以帮助我了解为什么我的循环省略了数组的第一个元素 (array[0])

守则

foreach ($a as $key => $val) {

        for ($i=0; $i<count($val); $i++) {
            $x = $i; //this helps me jump logical arguments without the use of else


            // First Test
            if (isset($val[$i+2]) && $x = $i) {

            //Do a bunch of stuff

                    if (isset(the stuff done above)) {
                    // do other things and reset $i to jump through the array
                    $i=$i+2;

                    }                 

                    else {
                        unset($things);
                        unset($otherthings);
                    }
                }
            }


            // Second Test
            if (isset($val[$i+1]) && $x = $i) {

            //Do a bunch of stuff

                    if (isset(the stuff done above)) {
                    // do other things and reset $i to jump through the array
                    $i=$i+1;

                    }                 

                    else {
                        unset($things);
                        unset($otherthings);
                    }
                }
            }

            // Third and final test
            if ($x = $i) {

               //do other things

            }

        }
}

问题

我似乎无法理解为什么,但是 for 循环或 IF 语句(我不能 100% 确定哪一个)未能通过数组 [0] 的第一个元素。

它从数组 [1] 开始运行良好,但即使我已经测试过 $x 确实 = 到 $i 并且因此测试 3 至少应该可以工作,循环似乎运行一个循环过去所有IF's 然后从 array[1] 开始工作。

我尝试过的

  • 我已经更改了for ($i=1; $i&lt;$val; $i++),并且从一开始就可以正常工作(例如不会省略任何内容)(但当然不能解决我的问题,因为我仍然缺少数组 [0])
  • 我已经在代码中测试了 echo $val[0] 在代码开头是否打印出来并且确实如此
  • 我还测试了$x = $i,这些也有效

这是其中一个让我觉得更改代码中的所有内容太愚蠢的问题之一,但是在整个堆栈溢出和谷歌搜索了很多类似问题之后,我似乎无法找出原因。

我写循环的方式一定有什么问题我看不到?

【问题讨论】:

    标签: php arrays for-loop


    【解决方案1】:

    使用$x == $i 来测试相等性,而不是$x = $i,这是一个赋值。

    【讨论】:

    • 在这些时刻,我很感激、谦卑和有点尴尬……这都是学习的一部分;)成功了,谢谢
    • @Jacob 没关系,我们将从小错误中吸取教训。 :):)
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2013-06-11
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多