0

I am trying to retrieve column data from a csv file. The first two columns return fine, but for some reason I get Notice: Undefined offset: 2 when I try to reference the 3rd column of csv data. Here is what I believe to be the relevant code in question:

$handle = fopen($csv_file, 'r');

while(($fileop = fgetcsv($handle,1024, $delimiter)) !== false) {
    echo $fileop[0]."<br/>";
    echo $fileop[1]."<br/>";
    echo $fileop[2]."<br/>";    //error occurs this line
}

The CSV file text:

THE GOLD CONNECTION,1760,2014-06-01
PINEFOREST JEWELRY,3034.25,2014-06-05
AMBERS DESIGN,2034.75,z
GOLD FALCON CUSTOM JEWELERS (PORT),78,
SUE'S JEWELRY,120,
JC JEWELERS,274,
ALTER'S GEM JEWELRY,74,
STALL JEWELERS,38,
ELEGANT JEWELERS,174,
ELEGANT JEWELERS,206,
SALEM'S JEWELERS,406,

How do I fix this? Thanks in advance

3
  • Hm... You don't have ending commas for the first three, but then the rest do. Commented Jun 18, 2014 at 18:48
  • @Fred-ii- commas don't seem to have an effect Commented Jun 18, 2014 at 18:50
  • Did you try getting rid of all the commas at the end, or did you make them all ending with a comma? Commented Jun 18, 2014 at 18:56

1 Answer 1

1

Use array_key_exists to verify that third index exists:

while(($fileop = fgetcsv($handle,1024, $delimiter)) !== false) {
    echo  $fileop[0]."<br/>";
    echo $fileop[1]."<br/>";
    echo array_key_exists(2, $fileop) ? $fileop[2]."<br/>" : "<br/>";    //error occurs this line
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.