How to Count the Number of Words in a File in PHP?

Posted on

Counting the number of words in a file is useful in many programs. In this post, we will discuss how to count the number of words in a file in a PHP script.

In PHP standard library, we have function str_word_count($str) which returns the number of words from a string $str. On the other hand, regarding files, we can open a file and read the content using PHP standard library functions fopen() and fgets(). Based on these, we can build a function to count the number of words in a file in PHP.

function get_word_cnt($file_fullpath) {
  $file = @fopen($file_fullpath, "r");
  if ($file === FALSE) {
    // error_log("Failed to open file $file_fullpath .");
    return -1;
  }
  $cnt = 0;
  while (!feof($file)) {
    $line = fgets($file, 8192);
    $cnt += str_word_count($line);
  }
  fclose($file);
  return $cnt;
}

Here, we read the file content in a while loop piece by piece. The fgets() function can not get an arbitrary large content. Otherwise, the PHP program will need quite a large memory for the $line object.

If there are failures, this function returns -1. Otherwise, it returns the number of words in the file.

Leave a Reply

Your email address will not be published. Required fields are marked *