0

Read a text file and display all lines ending with the letter A

Plz help it shows uninitialized char value 0 What is wrong?? <?php $f=fopen('mys.txt', 'r'); while (!feof) { $n=fgets($f); $m=strrev($n); if ($m[0]=='A') echo $n; } fclose($f); ?>

22nd Dec 2018, 4:25 PM
Lord Pharaoh
Lord Pharaoh - avatar
5 Respostas
+ 3
Lord Pharaoh, test this out on your side and tell me how it goes, I think the problem lies on the while loop, the feof() function expected a file handle as an argument. Also you can use substr() function with negative start index to read in from behind. <?php $f=fopen('mys.txt', 'r'); while (!feof($f))// while (!feof) { $n=fgets($f); //$m=strrev($n);// no need to reverse if(substr($n, -1) == 'A')// ($m[0]=='A') echo $n; } fclose($f); ?> Hth, cmiiw
22nd Dec 2018, 5:49 PM
Ipang
+ 2
Looks like the problem is that fgets() function reads the line without removing the new line character off the string buffer, can you change the code like this and try again? if(substr($n, -2) == 'A') If you write the mys.txt file with Notepad or something there's a possibility that line break character was '\r\n' instead of just '\n'. In that case, probably we'll have to do: if(substr($n, -3) == 'A') But if you write the file with code, using '\n' for line breaks -2 index for substr() function might do the work.
23rd Dec 2018, 9:00 AM
Ipang
+ 1
not working bro shows no output cannot understand this time there is no error message just blank screen
23rd Dec 2018, 6:24 AM
Lord Pharaoh
Lord Pharaoh - avatar
+ 1
Okay bro ... so can you show some example of the file content? maybe I can try to test in Playground. Also tell me, are you running this in Playground or your computer/laptop? P.S. It's kinda hard to tell with no error message ...
23rd Dec 2018, 6:57 AM
Ipang
+ 1
so basically my text file has 5 words INDIA CHINA GERMANY SPAIN AMERICA now i am running this on my laptop wamp server php version 7.0.4 using sublime text
23rd Dec 2018, 8:20 AM
Lord Pharaoh
Lord Pharaoh - avatar