Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

php - 为foreach()提供了无效的参数(Invalid argument supplied for 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.

(我经常碰巧处理可以是数组或null变量的数据,并用这些数据提供一些foreach信息。)

$values = get_values();

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

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

(当为foreach提供非数组数据时,会收到警告:)

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

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

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:

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

  • Casting $values to array

    (将$values为数组)

  • Initializing $values to array

    (初始化$values到数组)

  • Wrapping the foreach with an if

    (用if包装foreach)

  • Other (please suggest)

    (其他(请建议))

  ask by Roberto Aloi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(我偏爱的原因是,当您一无所有时,它不会分配空数组。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...