【问题标题】:Issue with: "Warning: Invalid argument supplied for foreach"问题:“警告:为 foreach 提供的参数无效”
【发布时间】:2011-05-31 10:21:26
【问题描述】:

我在数组上遇到了上述警告。

我完全理解警告是什么以及导致它的原因,并且我已采取一切措施来防止它,但是很遗憾,没有任何效果。

采取的步骤:

我已经检查了数组,如果不存在就声明它。

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)) 中,但我仍然收到此警告。

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

这让我发疯了。

【问题讨论】:

  • 你能 var_dump 你正在使用的变量并将结果发布到这里吗?
  • 你确定你检查的是正确的数组吗?或者它不会在循环内被覆盖?
  • var_dump 在我检查数组之前返回nullvar_dump 在我检查并声明它按预期返回array(empty) 之后。所以对象现在是一个数组,但每次尝试foreach 时我仍然会收到此警告

标签: php foreach reporting warnings


【解决方案1】:

尝试:

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

因为例如如果

$this->theVariables['associated'] 将是 1 这个数组分配永远不会达到:

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

(第二次测试也是如此)

关于 Ólafur Waages 的评论,请看Lazy evaluation

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

<?php
$fakeArray = 'bad';

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

var_dump($fakeArray);

输出

string(3) "bad"

【讨论】:

  • @Ólafur Waage 因为没有使用is_array 进行测试的示例代码,我只能猜测他遇到了懒惰的评估问题。 (例如在is_array 检查之前使用!is_empty(...) ||
  • @Designermonkey 然后请提供您尝试过的代码(或者更好的是,完整的代码)。因为is_array 通常是万无一失的。
  • 我将此答案标记为正确,因为我无法撤回问题。我们的服务器没有反映在每次部署所述代码时对代码所做的更改。我刚刚彻底检查了服务器上的代码,发现我的任何编辑都没有被应用。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    如果你真的需要遍历那个对象,先把它转换成一个数组:

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

    【讨论】:

      【解决方案4】:
      if (!$this->theVariables['associated'])
      

      检查数组是否存在。

      改为这样写:

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

      【讨论】:

        猜你喜欢
        • 2017-06-01
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多