0

I am trying to display data from a text file, each information on a new row, and the following code works but I get a "Notice: Undefined offset: 1, 2, 3" error messages. I'm not sure if it is because it has reached the end of the file. I don't understand arrays very well as I am a beginner. Also, the text file will be updated with new information so I need the code to be flexible.

Any help to solve this simple php notice message would be appreciated.

<?php

$data = file_get_contents('random.txt');
$rows = explode("\n", $data);

for($i = 0; $i < count($rows); $i++)

{
    $temp = explode('|', $rows[$i]);
    $random = $temp[0];
    $date = $temp[1];
    $time = $temp[2];
    $alphanumeric = $temp[3];

    echo $random . "<br />";
    echo $date . "<br />";
    echo $time . "<br />";
    echo $alphanumeric . "<br />";
}

?>

I get the following "Notice" message at the bottom of the php page...

Notice: Undefined offset: 1 on line 11

Notice: Undefined offset: 2 on line 12

Notice: Undefined offset: 3 on line 13

makaio
  • 1
  • It's probably just because there are blank lines at the end of the file. – Don't Panic Jun 20 '17 at 21:39
  • sigh, thank you kindly. I opened the text file and made sure there weren't any extra lines and all works fine. – makaio Jun 20 '17 at 21:52
  • no problem. The undefined offset notices occur because when you explode the blank lines, there's only one element `[0]` in the resulting array. – Don't Panic Jun 20 '17 at 21:54
  • Do you know how to prevent the offset notice? Each time I write to the text file I get the same error message. I've noticed there is a trim() option and also PHP_EOL, FILE_APPEND. – makaio Jun 20 '17 at 22:24
  • Actually, what I'd recommend is to use [`file`](http://php.net/manual/en/function.file.php) rather than `file_get_contents` to read the file contents directly into an array. You can use the `FILE_SKIP_EMPTY_LINES` option with that function. You can also use `foreach` rather than `for` to iterate the lines in order to avoid counting the array. – Don't Panic Jun 20 '17 at 22:27
  • beautiful! thank you. I am just a beginner but I am grateful to people like you who take the time to help others. – makaio Jun 20 '17 at 22:37
  • No problem. I think the linked "duplicate" question is useful to get a better understanding of exactly what "undefined offset" means, but doesn't quite explain why you'd be seeing it in this case. In general, if you can't tell why a notice like that is showing up, you can var_dump the variables in the line that generated the notice to get a better idea. – Don't Panic Jun 20 '17 at 22:46

0 Answers0