问题:“警告:为foreach提供的参数无效”

时间:2011-05-31 10:21:27

标签: php foreach reporting warnings

我在阵列上遇到上述警告时遇到了一些麻烦。

我完全明白警告是什么,是什么原因造成的,而且我已经采取了我可以采取的每一步措施来阻止它,但是唉,没有任何效果。

采取的步骤:

我已检查过该数组,如果不存在则声明它。

if(!$this->theVariables['associated']){
    $this->theVariables['associated'] = array();
   }

$this->theVariables['associated'] = $this->theVariables['associated'] || array();

没有任何影响。

我已将foreach包装在if中,检查数组是否为空(!empty()),它是否存在,它是一个数组(is_array()) ,然后甚至在foreach声明(foreach((array)$this->theVariables['associated'] as $item))中输入数组,但我仍然收到此警告。

由于我无法在此特定服务器上关闭错误报告,是否有其他方法可以停止显示此警告?

这让我疯了。

4 个答案:

答案 0 :(得分:1)

尝试:

if (is_array($this->theVariables['associated'])) {
  // your foreach here
}

例如,如果

$this->theVariables['associated']1永远无法访问此数组:

if(!$this->theVariables['associated']){
    $this->theVariables['associated'] = array();
}

(第二次测试同样如此)

关于ÓlafurWaages评论,请查看Lazy evaluation

例如,如果您的测试看起来像这样,您可能会遇到问题:

<?php
$fakeArray = 'bad';

if (empty($fakeArray) && !is_array($fakeArray)) {
    $fakeArray = array();
}

var_dump($fakeArray);

<强>输出

string(3) "bad"

答案 1 :(得分:0)

为什么不检查if (is_array($this->theVariables['associated'])){

答案 2 :(得分:0)

如果你真的需要循环遍历该对象,首先将其转换为数组:

foreach((array) $this->theVariable as $key => $value){
     echo $key . " = " . $value . "<br>";
 }

答案 3 :(得分:0)

if (!$this->theVariables['associated'])

检查数组是否存在。

改为写下:

if (!isset($this->theVariables['associated']) ||
   !is_array($this->theVariables['associated']))