Page 1 of 1

foreach error

Posted: Sat Aug 11, 2007 8:01 am
by m2babaey
Hi
I get error at the last line (when foreach begins):

Code: Select all

<td> 1st </td>
            <td> 2nd </td>
            <td> 3rd </td>
            <td> 4th </td>
            <td> 5th </td>
 
  </tr> <?php 
  foreach ($lines as nrow => $keyword){
$getbid="SELECT id FROM listing WHERE keyword LIKE %$keyword% ORDER BY maxb DESC LIMIT 5";
:? do you know where i am wrong?

Posted: Sat Aug 11, 2007 8:05 am
by Paw
First of all, 'nrow' is not a variable. You need to prepend a $.
Secondly you have to check:

Code: Select all

if(count($lines)>0)
before using the foreach-loop, otherwise you get a warning message.

Posted: Sat Aug 11, 2007 8:14 am
by kaszu
Note: warning message is not generated if array is empty. You don't have to check if it is empty or not.

Posted: Sat Aug 11, 2007 9:10 am
by Paw
kaszu wrote:Note: warning message is not generated if array is empty. You don't have to check if it is empty or not.
Sorry, I confused that with something else. For some reason I had database result sets in mind, which can be false when an error occured -- at least that has to be checked in advance. I'm getting old :-)

P.S.: And... well... even then checking for count doesn't make sense, either... Heck, what is wrong with me today... hehe

Posted: Sat Aug 11, 2007 9:28 am
by superdezign
Paw wrote:Sorry, I confused that with something else. For some reason I had database result sets in mind, which can be false when an error occured -- at least that has to be checked in advance. I'm getting old :-)

P.S.: And... well... even then checking for count doesn't make sense, either... Heck, what is wrong with me today... hehe
Maybe you were thinking in terms of this:

Code: Select all

while($condition)
{
    $foo[] = $data;
}

foreach($foo as $key => $value)
{
    // ....
}

Which is different than this:

Code: Select all

$foo = array();

while($condition)
{
    $foo[] = $data;
}

foreach($foo as $key => $value)
{
    // ....
}
Even then, you'd want is_array(), empty(), or isset(), not count() or sizeof().