Question

Hi the code below shows me selecting lines from a text file with a criteria. I want to know if i can count these lines, hopefully there is a simple way to do it i.e not using an array..... any help ?

Was it helpful?

Solution

Use a $count variable to keep track.
This should work -

$count = 0;
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false){
    $count++;
    echo '<p> '.$line.' </p>';
  }
}
echo $count;

OTHER TIPS

I am not sure I understood you well, is this what you want?

<?php
// What to look for
$search = 'red';
// Read from file
$lines = file('file.txt');
$count_lines=0;
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false)
    echo '<p> '.$line.' </p>';
    $count_lines++;
}
echo $count_lines;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top