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

问题描述

|| 我在数组上遇到上述警告时遇到了麻烦。 我完全理解警告是什么,以及警告的原因,并且我已尽力防止了警告,但可惜,没有任何效果。 采取的步骤: 我已经检查了数组,如果不存在则声明它。
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)
)中类型转换该数组,但我仍然得到此警告。 由于我无法关闭此特定服务器上的错误报告,因此没有其他方法可以停止显示此警告? 它让我发疯。     

解决方法

        尝试:
if (is_array($this->theVariables[\'associated\'])) {
  // your foreach here
}
例如,如果
$this->theVariables[\'associated\']
将是
1
永远不会达到此数组分配:
if(!$this->theVariables[\'associated\']){
    $this->theVariables[\'associated\'] = array();
}
(第二次测试也是如此) 至于ÓlafurWaages的评论,请看一下懒惰的评估。 例如,如果您的测试看起来像这样,您可能会遇到问题:
<?php
$fakeArray = \'bad\';

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

var_dump($fakeArray);
输出:
string(3) \"bad\"
    ,        为什么只是不跟ѭ14核对呢?     ,        如果确实需要遍历该对象,请首先将其强制转换为数组:
foreach((array) $this->theVariable as $key => $value){
     echo $key . \" = \" . $value . \"<br>\";
 }
    ,        
if (!$this->theVariables[\'associated\'])
不检查数组是否存在。 改写这个:
if (!isset($this->theVariables[\'associated\']) ||
   !is_array($this->theVariables[\'associated\']))