PHP: Count Lines of Code

posted in: Uncategorized | 0

As a coder, I am always doing research trying to find new and better ways of doing… everything. When I find something awesome, I save it to my collection. I quite enjoy when I stumble upon people sharing their own collections of code Snippets, so I have decided to start posting a few to share with anyone who might be looking for code snippets like I do.

This code snippet is a PHP function that given a directory path will count the lines of code of all files of a given file extension. It will also go recursively into sub directories. The $extentions array contains the file extensions you would like to count. It is built to ignore opening and closing php tags.

<?
function countLinesOfCode($path) {
   $lines = 0;
   $items = glob(rtrim($path, '/') . '/*');

   $extentions = array('php','css','js');

   foreach($items as $item) {

       if (is_file($item) AND in_array(pathinfo($item, PATHINFO_EXTENSION),$extentions)) {
           $fileContents = file_get_contents($item);
           preg_match_all('/<?(?:php)?(.*?)($|?>)/s', $fileContents, $matches);

           foreach($matches[1] as $match) {
               $lines += substr_count($match, PHP_EOL);
           }

       } else if (is_dir($item)) {
           $lines += countLinesOfCode($item);
           continue;
       }       

   }

   return $lines;}

var_dump(countLinesOfCode(dirname(__FILE__))); // int(31) (works for me)
?>

This snippet is a modified version of this answer on Stack Overflow: http://stackoverflow.com/a/5112406

My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

Leave a Reply