如何修复“Invalid Argument Supplied for Foreach()”PHP 错误

一旦 PHP 的内置 foreach 尝试迭代一个未被识别为数组或者对象的数据结构,就会触发“Invalid Argument Supplied for Foreach()”错误(为 foreach() 提供的参数无效)。

让我们看看一个代码片段:

<?php
function getList()
{
    //这里发生了几个错误,将返回布尔值 FALSE而不是数组/列表。
    //
    return false;
}
//从函数调用中检索数组。
$myList = getList();
//循环遍历 $myList 数组。
foreach ($myList as $arrayItem) {
    //对数组元素进行操作
}
?>

此代码的输出将导致“为 foreach() 提供的参数无效”错误。

让我们弄清楚它为什么会发生以及如何解决错误。

错误的主要原因是 getlist() 函数返回的是布尔值而不是数组。

需要注意的是 foreach() 命令只能迭代对象或者数组。

解决此错误可能非常简单。
我们所需要的只是在 foreach 命令被绕过之前检查。

下面的代码清楚地显示了如何解决错误:

<?php
function getList()
{
    //Assume some error occurs here and instead of
    //a list/array, a boolean FALSE is returned.
    return false;
}
//Get the array from a function call.
$myList = getList();
//Check if $myList is indeed an array or an object.
if (is_array($myList) || is_object($myList)) {
    //If yes, then foreach() will iterate over it.
    foreach ($myList as $arrayItem) {
        //Do something.
    }
} else //If $myList was not an array, then this block is executed. 
    {
    echo "Unfortunately, an error occurred.";
}
?>

在 PHP 中的foreach()

在 PHP 中,foreach() 构造允许直接迭代数组。

它只对对象和数组进行操作。
在具有不同数据类型的变量上使用它后,会导致错误。

在 PHP 5 中,一旦 foreach 开始首先执行,内部数组指针将自动重置为数组的第一个元素。
因此,没有必要在 foreach 循环之前调用 reset() 函数。

日期:2020-06-02 22:15:48 来源:oir作者:oir