faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

23 of 27 people (85%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

Can I read the number of lines in a file without looping?

Feb 3rd, 2002 03:30
Philip Olson, Jens Clasen, Per M Knutsen,


Yes, there are a few ways.  First, if running linux and able to run
shell commands, then the unix command 'wc' is most likely available. 
The following will count the number of lines in a file:
  wc -l
Let's use the special `backtick` operator to execute our command, using
exec() and various other type functions is also possible.  Example:
<?php
  $filename = 'somefile.txt';
  $count    = trim(str_replace($filename,'',`wc -l $filename`));
?>
See:
  http://www.php.net/manual/en/language.operators.execution.php
Another way is to use the PHP file() function.  file() stores each line
of a file as an element of an array and from there we can do a count. 
For example:
<?php.
  $filename = 'somefile.txt';
  $lines    = file($filename);
  $count    = count($lines);
?>
See:
  http://www.php.net/file
  http://www.php.net/count 
Going through 'wc' is more efficient, either will do the job.  Note that
wc -l also returns the filename, so we removed that.