0

I'm extremely new to php and I am trying to get how many lines there are in my file. I am currently using some code I found online.

$file = "filename";
$lines = count(file($file));

This returns 1. and there are MANY more lines than that. Any insight? Does it have something to do with new line characters? I did a $fh = file($file); split('\n', $fh); and the count of that is still 1....so I am not sure.

  • Possible duplicate: http://stackoverflow.com/questions/2162497/efficiently-counting-the-number-of-lines-of-a-text-file-200mb – John Giotta Aug 16 '11 at 13:50
  • What you are doing should work - what happens when you `print_r(file($file))`? How many elements does the output have? Does it contain all of your file? Also, what platform are you working on? It's not OSX by any chance is it...? – DaveRandom Aug 16 '11 at 13:51
  • Are you sure that the file has more than one line? – Ed Heal Aug 16 '11 at 13:52
  • Returns 0...and I think it's empty.....Also no I am not on osx. I'm on ubuntu –  Aug 16 '11 at 13:55
  • The file is pretty large and it definitely has more than 1 line. –  Aug 16 '11 at 13:56
  • Sounds like you not actually managing to open your file, are you sure the path makes sense in the context it's used in your script? Try and `print(getcwd())` and make sure your working in the directory you think you are. Also `var_dump(is_file($file))` and `var_dump(is_readable($file))` to make sure PHP can see your file, and read it - you might need to chmod it... – DaveRandom Aug 16 '11 at 13:58
  • Thanks. You're actually right I just fixed the issue and implemented @corum 's solution below and it works. The issue was `$file` was being used as a global variable when it was actually a local one. Rookie mistake...kind of embarrassing. Thanks everyone –  Aug 16 '11 at 14:03

1 Answers1

1

You can try this :

$lines = 0;

if ($fh = fopen('file.txt', 'r')) {
  while (!feof($fh)) {
    if (fgets($fh)) {
      $lines++;
    }
  }
}
echo $lines; // line count
Elorfin
  • 2,487
  • 1
  • 27
  • 50