The issue isn't with foreach, it's with the type of variable you are iterating, or attempting to iterate I should say. The PHP
foreach [php.net] control structure will never throw a warning on an empty array. It will throw a warning because the argument you are offering is
not an array. That is why you don't receive the warning when you cast it as an array.
rocknbil is showing you how to overcome that by first initializing the variable before populating it with data and then iterating over it. For example, lets say you expect the array to come from checkboxes that were posted. PHP by default will create an array for you if you set them up correctly in your form by using the brackets. However, what if the array of values is coming from somewhere else where it may or may not be an array? It can happen, and if you code long enough you will find that it will indeed happen. What to do? Cast it!
$myExpectedArray = (array) $arrayFromSomewhere;
foreach ($myExpectedArray as $key => $value) {
// process the array
}
You are doing the same thing, just inside the construct. You can do it either way without issue.
I think what the members here are saying is that if you are uncertain as to the origin of the variable, meaning you don't know if it is an array or not, you should probably be doing some other form of editing and casting of the variable prior to iterating over it with a control structure and processing.