foreach error

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
m2babaey
Forum Contributor
Posts: 364
Joined: Sun May 20, 2007 9:26 am

foreach error

Post 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?
Paw
Forum Newbie
Posts: 20
Joined: Tue Jul 17, 2007 10:27 am

Post 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.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Post by kaszu »

Note: warning message is not generated if array is empty. You don't have to check if it is empty or not.
Paw
Forum Newbie
Posts: 20
Joined: Tue Jul 17, 2007 10:27 am

Post 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
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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().
Post Reply