-2

i have a doubt.this is my foreach loop

<table>
<?php foreach($this->msg as $l): ?>
 <tr><td>
 <a href="index.php/downloads?id=<?php echo $l->id;?>"><?php echo $l->name;?></a>
 </td></tr>
 <?php endforeach; ?>
  </table>

where $this->msg is an array of results from db. this shows warning

Warning: Invalid argument supplied for foreach() 

how should i resolve this?

user007
  • 61
  • 1
  • 2
  • 14
  • 3
    At the time you call this code, `$this->msg` is **not** an array. You should check its type (try `is_array`) before entering the loop or instantiate it to an empty array on declaration, eg `private $msg = array();` – Phil Oct 21 '13 at 05:22
  • use var_dump and check $this-msg value – naveen goyal Oct 21 '13 at 05:23
  • check if $this->msg an array `var_dump($this->msg)` – vaibhavmande Oct 21 '13 at 05:23
  • when var_dump gives before it returns null. but after i run the above code actually i got the correct array details from db also with the error message.
    – user007 Oct 21 '13 at 05:45
  • @Phil : thank you phil..i solved it using the if(empty($this->msg)) function. – user007 Oct 21 '13 at 05:48

3 Answers3

0

If your not sure what your passing through foreach then i recommend you to check first using is_array function. Something like this:

if (is_array($message)) {

foreach ($message as $text) {
//do something

 }
}

Use var_export or var_dump to check what your passing to foreach loop.

Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22
0

the answer is:

if(empty($this->msg)){
}
else{
<table>
<?php foreach($this->msg as $l): ?>
<tr><td>
<a href="index.php/downloads?id=<?php echo $l->id;?>"><?php echo $l->name;?></a>
</td></tr>
<?php endforeach; ?>
 </table>
}
user007
  • 61
  • 1
  • 2
  • 14
0

Try this:

First check output from $this->msg.
If it is array type && not empty then and then you can pass to the foreach loop.

You can check array using is_array() function
&&
You can check array is empty using empty() function.

- Thanks

Anand Solanki
  • 3,419
  • 4
  • 16
  • 27