Pergunta

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 ?

Foi útil?

Solução

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;

Outras dicas

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;
?>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top