for循环不处理数组的第一个元素

时间:2016-06-27 12:19:05

标签: php arrays for-loop

我对代码中的一个问题感到困惑,并希望其他人可以帮助我解释为什么我的循环省略了数组的第一个元素(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]的第一个元素运行。< / p>

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

我尝试了什么

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

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

一定有什么不对的我在编写循环的方式中看不到?

1 个答案:

答案 0 :(得分:6)

使用$x == $i来测试相等性,而不是$x = $i,这是一项任务。

相关问题