Jump to content

Recommended Posts

Hi

 

I have made the code below that outputs the contents of a CSV file into a table. The code works fine however on my server host CGI error log, it says

 

PHP Warning:  Invalid argument supplied for foreach() in "my_php_file_name" on line 83
 

do
{
    $array = fgetcsv($filehandle, 65, ",");
    echo "<tr>";
    foreach ($array as $tableformat)
    {
    echo "<td>".$tableformat."</td>";    
    }
    echo "</tr>";
    $nextrow++;
}
while ($nextrow <= $lines);
 

 

$lines refers to the number of lines in the CSV file and $nextrow represents the integer value 0.

 

Although it is working, could someone please explain to me why this message appears so that I can correct it and learn from this experience. Thank you.
 

Edited by MFA
Link to comment
https://forums.phpfreaks.com/topic/276405-foreach-error/
Share on other sites

Since the warning specifies the invalid argument is located in the foreach, you can ignore the do...while loop and the $nextrow and $lines variables.

 

It has to do with what $array contains.  It must not actually be an array, so it's likely either NULL or FALSE, from what I've just read in the docs.

 

Try doing checks on the array variable, testing if it is empty, false, or null before you run the foreach loop which assumes that it is an array.

 

Also, the docs seem to use a while() loop with fgetscsv().  You might want to look into that.

 

nbst

Link to comment
https://forums.phpfreaks.com/topic/276405-foreach-error/#findComment-1422379
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.