Php count number lines file

Counting all lines of code in .php files given a dir

Keep in mine this is counting newlines, not end of line character ; . For example, the line below will be considered one line.

var_dump($files); echo 'something'; exit; 

It also counts lines without any PHP code, e.g. the below code will be 4 lines.

Let me know if it (a) shouldn’t match empty lines, (b) should match semi colons instead (will need to ensure they are not appearing within a string) and/or (c) it should match the opening and closing tag (will be easy as changing $matches[1] in the foreach to $matches[0] ).

@alex: man there is a huge problem. It doesn’t go recurvise under sub-dir. That’s a huge problem. I guess we could change glob to match everything inside the path, and in the foreach if it’s a dir (is_dir()) we should go recurisvely into that sub-dir. But i don’t have such expierence (anyway +1 for the moment)

Читайте также:  Цикл фор питон кратко

PHPLOC

A tool for quickly measuring the size and analyzing the structure of a PHP project.

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

recursive version of alex function

function countLinesOfCode($path) < $lines = 0; $files = glob(rtrim($path, '/') . '/*'); foreach($files as $file) < if (is_dir($file))< if ($file=='.' || $file=='..') continue; $lines+=countLinesOfCode($file); >else if (substr($file,-4)!='.php') continue; echo 'Counting on ' . $file .'
'; $fileContents = file_get_contents($file); preg_match_all('/<\?(?:php)?(.*?)(?:$|\?>)/s', $fileContents, $matches); foreach($matches[1] as $match) < $lines += substr_count($match, PHP_EOL); >> return $lines; >

I made it work based on this Answer and the documentation for RecursiveDirectoryIterator.

$path = realpath( '/path/to/directory' ); $lines = $files = 0; $objects = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ), RecursiveIteratorIterator::SELF_FIRST ); foreach( $objects as $name => $fileinfo ) < if ( !$fileinfo->isFile() ) continue; if( false === strpos( $name,'.php' ) ) continue; $files++; $read = $fileinfo->openFile(); $read->setFlags( SplFileObject::READ_AHEAD ); $lines += iterator_count( $read ) - 1; // -1 gives the same number as "wc -l" > printf( "Found %d lines in %d files.", $lines, $files ); 

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Count Lines in File in PHP

To count the number of lines in a file in PHP, you can use one of the following approaches:

Use the file() function

This function reads the entire file into an array, with each line of the file as an element in the array. Then, use the count() function to count the number of elements in the array.

Here is an example of how to count lines in file in PHP using the file() method.

Note that this approach counts empty lines that exist within the file.

This code assumes that you have file.txt in current folder. You can provide relative path or absolute path based on the preference.

Use the file_get_contents() function

Using the FILE_IGNORE_NEW_LINES flag

Here, we can count lines in a file using the file_get_contents() function with the FILE_IGNORE_NEW_LINES flag. This function reads the entire file into a string, ignoring newline characters. Then, use the substr_count() function to count the number of newline characters in the string.

The FILE_IGNORE_NEW_LINES ignores the newlines that are empty, and simply focuses on lines with characters.

Using the FILE_SKIP_EMPTY_LINES flag

Here we make use of the file_get_contents() function alongside the FILE_SKIP_EMPTY_LINES flag to count lines in file.

This function reads the entire file into a string, skipping empty lines. Then, use the substr_count() function to count the number of newline characters in the string.

Here is an example script on how to use the function.

The FILE_SKIP_EMPTY_LINES ignores the newlines that are empty, and simply focuses on lines with characters.

Use the fopen() and fgets() functions

Another approach we can take is count lines in file using a loop. This approach makes use of the fopen() and fgets() function to reads the file line by line, incrementing a counter variable for each line.

Note that this approach counts empty lines that exist within the file.

fopen() method with r is used to open file in read mode.

fgets() method is used to get line from file pointer in PHP.

That’s all about how to count lines in file in PHP.

Was this post helpful?

Share this

Author

Remove Last Character from String in PHP

Table of ContentsUse the substr() functionUse the rtrim() functionUse the mb_substr() functionUse the preg_replace() functionUse the str_split() and array_pop() function This article explains different ways to remove the last character from a string in PHP Use the substr() function To remove last character from String in PHP, use of the substr() function and pass a […]

Check if Variable is Array in PHP

Table of ContentsUsing the is_array() functionUsing the gettype() functionUsing the typesetting syntax Using the is_array() function To check if variable is array in PHP, use is_array() function. The is_array() function is a built-in function in PHP that takes a variable as an argument and returns a Boolean value indicating whether the variable is an array. […]

Split String by Comma in PHP

Table of ContentsUse the explode() functionUse the str_getcsv() functionUse the preg_split() functionUse the mb_split() function This article explains how to split a string by comma in PHP using different approaches. Use the explode() function To split string by comma, we can make use of the explode function. This function splits the string by the specified […]

Format Number to 2 Decimal Places in PHP

Table of ContentsUsing the round() functionUsing the number_format() functionUse sprintf() functionUse the floatval and number_format function Using the round() function To format a number to 2 decimal places in PHP, you can use the round() function and pass the number and 2 as arguments to the round() function. Here is an example of how to […]

Check if Array is Empty in PHP

Table of ContentsUse empty() functionUse count() functionUse array_key_exists() functionUse array_filter() functionUse array_reduce() function Use empty() function To check if an array is empty in PHP, you can use the empty() function. This function accepts an array as its argument, and it returns true if the array is empty and false if the array is not […]

Replace Space with Underscore in PHP

Table of ContentsUsing str_replace() MethodUsing preg_replace() Method Using str_replace() Method Use the str_replace() function to replace with underscore in PHP, for example: str_replace(» » , «_», $str). str_replaces() returns new String with old character space( ) replaced by underscore(_) [crayon-64bb29810e99f381405381/] [crayon-64bb29810e9a5025609098/] We used str_replace() to replace space with underscore in PHP. str_replace() replaces all instances […]

Источник

PHP Exercises : Count number of lines in a file

Write a PHP script to count number of lines in a file.

Note : Store a text file name into a variable and count the number of lines of text it has.

Sample Solution:

There are 5 lines in a6924e70-5a4c-11e7-b47b-99347412a245.php

Flowchart: Count number of lines in a file

basename() function: The basename(path,suffix) function is used to get the filename from a path.

count() function: The count() function is used to count the elements of an array or the properties of an object.

Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

stdClass is PHP’s generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out).

It is useful for anonymous objects, dynamic properties, etc.

An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array. Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.

'; $stdInstance = json_decode($json); echo $stdInstance->foo . PHP_EOL; //"bar" echo $stdInstance->number . PHP_EOL; //42 //Example with associative array $array = json_decode($json, true); echo $array['foo'] . PHP_EOL; //"bar" echo $array['number'] . PHP_EOL; //42
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How to count the number of lines in a text file using PHP

Hello, I have posted several posts on working with a text file in PHP. Some of those were really helpful to the learners. Like
How to read a particular line from a text file in PHP
Fetching Text Data From a Text File Using PHP
Save HTML Form Data in a (.txt) Text File in PHP
But here in this post, I am going to show you How to count the number of lines in a text file using PHP.

Count the number of lines in a text file using PHP

To count the number of lines in a text file in PHP we need to use these below PHP function:

To get a better Idea you may read this post, this post is very similar to this one How to read a particular line from a text file in PHP You just need to extend a single line.

So let’s create a text file first.

Hello I am from line no 1 Hi I am from line no 2 hello again I am from line no 3 Hey I am from line no 4

Now you need to count the number of lines in this text file. Here we have 4 lines.

Save this file with any filename. Here I am going to save it as mytextfile.txt

PHP program to count the number of lines in a text file :

This above program will give you the number of lines in a text file.

Special note: The file() function actually returns an array. So here $all_lines variable holds the whole text file as an array. count() function will count the number of elements in the array.

Источник

Оцените статью