In the process of using PHP to develop projects, you may encounter this warning:
PHP Warning: Invalid argument supplied for foreach()
This warning is usually due to the The foreach() function passed in a non-array parameter, causing PHP to be unable to perform the iteration operation, thus throwing this warning. So, how to solve this problem? This article will introduce you to several possible solutions.
For the parameters passed in by the foreach() function, you need to explicitly judge to ensure that they are array types. You can use the PHP built-in function is_array() or the function gettype() to complete this judgment. For example:
if (is_array($arr)) { foreach ($arr as $val) { // do something } } else { // 参数非数组,抛出异常或者返回错误码 }
Traversing an empty array in foreach() will also trigger a similar warning, so you need to Determine whether the array is empty. This can be achieved using the empty() function. For example:
if (!empty($arr)) { foreach ($arr as $val) { // do something } } else { // 数组为空,抛出异常或者返回错误码 }
If the parameters passed in may be empty, you can use the OR operator before the foreach() function to assign the parameters Assign default value. For example:
foreach ($arr ?? [] as $val) { // do something }
So even if $arr is empty, if the ?? operator is used, the warning will not be triggered in foreach().
Finally, it should be noted that there are many functions that may generate warnings in PHP, not just foreach() function. When writing code, you need to carefully read the function documentation to understand the usage of the function and possible warnings so that you can judge and handle it when using it.
To sum up, there are many solutions to PHP Warning: Invalid argument supplied for foreach(). When writing PHP code, you need to pay special attention to the legality of the parameters passed into the function to avoid similar warnings.
The above is the detailed content of Solution to PHP Warning: Invalid argument supplied for foreach(). For more information, please follow other related articles on the PHP Chinese website!