2

I am reading from a csv file containing thousands of lines.

Now some lines are not properly formatted and hence when I try to read a particular index in a loop, I get Undefined offset errors.

I want to simply remove those lines. And for that purpose I have to identify which lines are causing problems.

Here is what is happening inside of loop:

$i=0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 2048,",");
$idx=$line_of_text[5];
$i++;
//do something else
}

The code works perfectly but I get 10-15 errors Undefined offset: 5 in filepath Now it is really difficult to determine those lines by just looking at the file. So is there a way to check if the row contains index 5 element and if not then show row number? I tried isset but it is not working.

Ahmar

2 Answers 2

4
"I tried isset but it is not working"

isset must work. Try this:

if(isset($line_of_text[5]))
{
    $idx=$line_of_text[5];
}
else
{
    print "incorrect line: $i\n";
}
Sign up to request clarification or add additional context in comments.

Comments

2

You could use

if( array_key_exists(5, $line_of_text) ) {
    $idx=$line_of_text[5];
} else {
    print "incorrect line: $i\n";
}

Or

if ( count($line_of_text) >= 6 ) {
    $idx=$line_of_text[5];
} else {
    print "incorrect line: $i\n";
}

But isset($line_of_text[5]); should also work.

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.