Title rewritten to: "Invalid argument: The argument supplied to foreach() is invalid"
P粉546138344
P粉546138344 2023-08-21 12:14:09
0
2
446
<p>It's common for me to deal with data that can be either an array or an empty variable, and feed that data to some <code>foreach</code>. </p> <pre class="brush:php;toolbar:false;">$values ​​= get_values(); foreach ($values ​​as $value){ ... }</pre> <p>When you provide data that is not an array to foreach, you will receive a warning: </p> <blockquote> <p>Warning: Invalid argument supplied for foreach() in [...]</p> </blockquote> <p>Assuming that the <code>get_values()</code> function cannot be refactored to always return an array (backward compatibility, unavailable source code, or other reasons), I would like to know how to avoid these warnings What is the cleanest and most efficient way:</p> <ul> <li>Cast <code>$values</code> to array</li> <li>Initialize <code>$values</code> to an array</li> <li>Wrap <code>foreach</code></li> in <code>if</code> <li>Other (please provide suggestions)</li> </ul></p>
P粉546138344
P粉546138344

reply all(2)
P粉635509719

how about this? It's more concise and it's all in one line.

foreach ((array) $items as $item) {
 // ...
 }
P粉517814372

Personally, I think this is the cleanest - not sure if it's the most efficient, pay attention!

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

The reason for my preference is that it doesn't allocate an empty array when you don't have any content at all.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template