0

I'm trying to read a csv file and then store the first and the 21st column in an associative array such that the 1st column becomes the key and 21st column becomes the value.

Later I would want to pull records based on the "key". The PHP file containing the code is upload.php

$calls = array();
$file_handle = fopen($C1.".File.csv","r"); // $C1 is defined before.
 //Just appending something to the file name. This file exists. 
while (!feof($file_handle) ) {
    $line= fgetcsv($file_handle, 1024);
    $calls[$line[0]] = $line[20]; //Line 94 of this file

}
fclose($file_handle);
print_r($calls);

I get this error

Undefined offset: 20 in upload.php on line 94

Where am I going wrong.

4
  • What is in upload.php on line 94? Because you don't use offset 24 anywhere here so your problem must be somewhere else. Commented Mar 13, 2013 at 22:07
  • You're missing a comma in that row. Or it's possible the entire line is blank. var_dump($line); Commented Mar 13, 2013 at 22:10
  • Sorry offset 20 in this case.. Not 24 Commented Mar 13, 2013 at 22:10
  • Consider using fgetcsv() function manual: php.net/manual/en/function.fgetcsv.php Commented Mar 13, 2013 at 22:22

1 Answer 1

1

The twentieth "column" in a zero-indexed array would be $line[19]

update as per your comment (and subsequent edit):

The error is clearly pointing out at some point during the loop $line[20] is not set - If each line has a suitable number of columns then the only other reason I can think of is that there is an empty line at the end of the CSV file.

Eg.

1.  foo, bar, baz
2.  a  , b  , c
3.                    <-- empty line as a result of carriage return

so... you want to check that trim($line)!='' before fgetcsv and/or as part of good error-handling check that the array's length is greater than the highest index you are trying to read.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.but I don't think thats the error. The csv that I'm trying to read has around 50 columns.

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.