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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…