0

I've been getting this below error:

PHP Warning:  Invalid argument supplied for foreach() in /home/~accountname~/public_html/index.php on line 140

This is the code for line 40;

<p>
    <?php foreach ($Homes3 as $Home) {
          echo $Home['home_3'];
      } ?>
</p>

For the best part of today and don't have a clue why, It's been working fine before today.

CDspace
  • 2,551
  • 17
  • 31
  • 35
aMason
  • 1
  • 1
    You have to provide more code, where does the variable $Home3 come from? – alanfcm Jun 05 '18 at 16:47
  • Is `$Homes3` something you can iterate over? It may not be what you expect it to be. – Kisaragi Jun 05 '18 at 16:48
  • 1
    **Just use `var_dump($Homes3)` to find out what you have in that variable.** I reckon it's going to be `null` or `false` you're getting from database query returning empty result, or something like that. – Smuuf Jun 05 '18 at 16:48
  • Check out this very thorough answer: https://stackoverflow.com/a/14854568/3968358 – Andrew A. Jun 05 '18 at 16:48
  • 1
    You're saying line 40, yet error is on line 140 – abr Jun 05 '18 at 17:07
  • Also, it may mean that $Homes3 is not an object valid for the foreach, dump it's content to see what is inside – abr Jun 05 '18 at 17:07

1 Answers1

1

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.

James
  • 4,317
  • 4
  • 33
  • 45