Undefined array key

This issue is driving me mad.
Here’s the part of my code that’s causing the problem:
if ($file = fopen(“Letters_db.txt”, “r”))
$lineoftextfile = fgets($file);
$Field = explode("|",$lineoftextfile);
if ($Field[1] == “Y”)

The Letters_db.txt Is a multi-line text document created by exporting from a spreadsheet.
When I run the script in XAMPP, it runs to completion but generates warnings like this
Warning : Undefined array key 1 in C:\xampp\htdocs…php on line 27
for every line in which I test on the value in one of the $Field cells.
If I echo $Field[1], it shows most lines have a “Y” in this field.
I’ve searched the net for hours on this but to to avail. Any suggestions would be very much appreciated.
Best regards

You should ALWAYS trim, then validate all input data before using it. After you explode the data, you should use array_map(), with php’s trim function as the call-back function, on $Field, in order to trim each element in the array. This will remove any white-space characters surrounding the values, which will include the new-line character(s) on the last element.

Next, if a line doesn’t contain any ‘|’ character, $Field[1] won’t exist. If this is an expected/normal condition ($Field[0] contains the entire line), you would need to test if $Field[1] isset() before testing the value in it.

If this is an unexpected condition, i.e. every line should contain at least one ‘|’ character, you would either need to find and correct the problem with the input data, ignore the line of data, or display an error message.

One thing that might cause an unexpected ‘empty’ line, would be if php is wrongly detecting pairs of new-line characters \r\n or \n\r in the file. Php could be detecting the actual line, followed by a line containing just a new-line character. After the explode() only $Field[0] would exist and contain a new-line character, which after the suggested trim operation, would be empty. You could then just test and ignore these empty lines of data.

Thank you for the prompt reply. I’d previously tried testing on trim($Field[1]), but being just a text file, the data file is easy to inspect and I can’t see any leading or trailing white spaces. And there are no empty first cells. I’m testing whether $Field[1] == “Y” and echo $Field[1] shows either Y or null as expected.
I’ll wrestle further with this along the lines you’ve suggested. Fingers crossed.
Thanks again.

I’ve cracked it!!!
The test if $Field[1] isset() revealed the problem.
The Report lines were in a loop {while(!feof($file))
and my txt database had a blank line at the end of it.
I feel such a pudding for not spotting this.
Thanks for your help.
I owe you a pint if you’re ever in the north of England.
Best regards

That’s why we trim() the input first. There’s usually an ending whitespace in files. Then validating that the line contains your separator is good practice too. As stated by phdr.

Sponsor our Newsletter | Privacy Policy | Terms of Service