为 foreach() 提供的参数无效 [英] Invalid argument supplied for foreach()

查看:32
本文介绍了为 foreach() 提供的参数无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常会处理可以是数组或空变量的数据,并用这些数据提供一些 foreach.

It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.

$values = get_values();

foreach ($values as $value){
  ...
}

当您使用非数组数据为 foreach 提供数据时,您会收到警告:

When you feed a foreach with data that are not an array, you get a warning:

警告:为 [...] 中的 foreach() 提供的参数无效

Warning: Invalid argument supplied for foreach() in [...]

假设不可能重构 get_values() 函数以始终返回一个数组(向后兼容性,源代码不可用,无论其他原因),我想知道哪个是最干净和最避免这些警告的有效方法:

Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:

  • $values 转换为数组
  • $values 初始化为数组
  • if
  • 包裹 foreach
  • 其他(请提出建议)
  • Casting $values to array
  • Initializing $values to array
  • Wrapping the foreach with an if
  • Other (please suggest)

推荐答案

我个人认为这是最干净的 - 不确定它是否最有效,请注意!

Personally I find this to be the most clean - not sure if it's the most efficient, mind!

if (is_array($values) || is_object($values))
{
    foreach ($values as $value)
    {
        ...
    }
}

我偏爱的原因是它不会在你一无所有的情况下分配空数组.

The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.

这篇关于为 foreach() 提供的参数无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆