search

Home  >  Q&A  >  body text

Title rewritten as: "The parameters of the foreach() function are invalid"

<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 foreach with data that is not an array, you will receive a warning: </p> <blockquote> <p>Warning: Invalid argument supplied in 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 any other reason), I would like to know how to avoid these warnings What is the cleanest and most efficient way: </p> <ul> <li>Convert <code>$values</code> to an 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><br /></p>
P粉419164700P粉419164700471 days ago540

reply all(2)I'll reply

  • P粉811349112

    P粉8113491122023-08-22 10:58:44

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

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

    reply
    0
  • P粉771233336

    P粉7712333362023-08-22 00:25:34

    Personally, I think this is the cleanest - not sure if it's the most effective, mind you!

    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 anything to begin with.

    reply
    0
  • Cancelreply