24 of 110 menu

Number of Lines PHP

Number of Lines in Text

If you have some text with line breaks, the number of lines can be calculated as follows:

<?php $str = '123\n456\n789'; echo substr_count($test, '\n') + 1; ?>

The point is that a line break is an invisible character \n. Using the function substr_count we count the number of these characters in our text, but it turns out to be 1 less than the actual lines. Therefore, we add one.

Number of Lines in a File

To count the number of lines in a file, you can use the method described above, or you can do it like this:

<?php // Consider the file as an array: $arr = file($file); // Count the number of lines in the array: echo count($arr); ?>

Please note that the first method is more optimal and works faster.

English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline