This will be because the variable $Home3
does not satisfy the requirements of foreach
construct, which requires the first parameter to be array.
When you don't know for sure a variable or array will always be set somewhow, you should initialise it in your code. I cannot give an example of that as the code provided is just output.
But it would look something like this:
$Homes3 = []; // This sets it to an empty array
Then you have the code which sets it, such as from a database query or form data.
Alternatively, if the above is not possible, you can check if it's an array before you try to use it. The first suggestion is better as you are managing your arrays correctly, and an empty array used in foreach
will simply do nothing and won't produce errors or warnings. But sometimes, especially in older code, it's not always possible.
if (is_array($Homes3)) {
foreach ($Homes3 as $Home) {
echo $Home['home_3'];
}
}
You could have an else that outputs another message if it's not array, e.g. "no data found" (or something better).
All this said, as you only echo one array key ($Home['home_3']
) you could do away with the loop and just do this:
echo isset($Homes['home_3']) ? $Homes['home_3'] : 'No data found';
But maybe your code is just for an example.