Reputation: 1068
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
Upvotes: 2
Views: 2196
Reputation: 94682
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.
Upvotes: 2
Reputation: 23749
"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";
}
Upvotes: 4