The PHP warning "Invalid argument supplied for foreach()" indicates that the given argument is not a valid array when iterating using the foreach construct.
The warning is triggered when the argument passed to foreach is not an array. This can occur for several reasons:
<code class="php">// Invalid argument: not an array foreach ($nonArrayVariable as $item) { // Error } // Invalid argument: empty array $emptyArray = []; foreach ($emptyArray as $item) { // Error } // Invalid assignment: assigns a string instead of an array $someVariable = 'some-string'; foreach ($someVariable as $item) { // Error }</code>
To resolve this warning, ensure that the argument passed to foreach is a valid array. You can do this by:
Here is an updated example using is_array():
<code class="php">if (is_array($variable)) { foreach ($variable as $item) { // Now safe to iterate } }</code>
The above is the detailed content of Why Am I Getting the \'Invalid argument supplied for foreach()\' Warning in PHP?. For more information, please follow other related articles on the PHP Chinese website!