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.
$values = get_values();
foreach ($values as $value){
...
}
When you feed a foreach with data that are not an array, you get a warning:
Warning: Invalid argument supplied for foreach() in […]
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:
- Casting
$valuesto array - Initializing
$valuesto array - Wrapping the
foreachwith anif - Other (please suggest)
There are three reasons that may cause this error:
A bug in the program. For example, get_values() is expected to return an array, but it returns something else. In this case you must start debugging the code, find the reason why get_values() doesn’t return an array, and fix it.
get_values() may return an array or indicate that there is no data at all, by returning null (or false). In this case, you must add a condition which explicitly checks for this value, i.e.
Here, PHP will be able to help you, by raising an alarm, when unexpected data type (i.e. neither null or array) would be provided (which means the bug in the code and you have to debug it again).
The code is just carelessly written and may return anything, so all you want is to get rid of this warning. But the most important part about warnings is that a programmer should never "avoid" (in the meaning or "silence") them.
Warnings are programmer’s friends, so don’t waste their power. Properly organize your code the way it would only return expected data types. This way you will never get false alarms that have to be silenced. And at the same time PHP will be able to help you when unexpected data type would be provided (meaning that some code or input is not okay).
When you have no control on the input data it would be a good idea to validate it before processing. In case an array is obligatory, then return an error and stop processing. In case an array is optional, initialize it as empty array. And so you won’t see this error again.
Only if don’t care whether your input is boolean, or string or actually iterable you may use the approach below, which purpose is just to sweep the dirt under the rug: