无法理解PHP代码示例

I've been looking around to see if anyone else has dissected this code already, but that has proven to be futile. I'm having some trouble understanding what's happening in this php code sample from here.

I'm still currently very new to programming and PHP as a whole so I'm hoping someone can give me a clean explanation (I have read the documentation, but I still fail to fully understand the code)

I'm currently tackling on a project to convert an uploaded CSV file into an array and then into a database. The sample code is below:

Example #1 Read and print the entire contents of a CSV file

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }
    }
    fclose($handle);
}


?>

I guess my problem really is with understanding the fgetcsv method, but if someone could provide me with a breakdown it would really be appreciated.

$row = 1;

Sets the initial number of rows processed.

if (($handle = fopen("test.csv", "r")) !== FALSE) {

Attempts to open the file (for reading only), continuing only if it can.

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

Iterates over each line in the CSV (with a maximum length of the row being 1,000 characters and the field delimiter being a comma), continuing only if it can, pulling the row out as an indexed array of the fields.

$num = count($data);

Gets the number of fields in the row.

echo "<p> $num fields in line $row: <br /></p> ";

Outputs the number of fields in the given row.

$row++;

Increments the row number.

for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br /> "; }

Iterates over each field in the row and outputs its value.

fclose($handle);

Closes the file.

fgetcsv reads your csv row-by-row.

It return ana associative array. If you have 10 columns in the csv for example:

csv1,csv2,csv3,...csv10 the $data variable each cycle will be an array like (csv1 => "value"1 ... csv10->"value10")

So your code print first the num of columns of the csv file

  count($data)

then iterate the row taken from csv and print all the columns values

for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />
";
    }

This is done for each row of the file