Display multiple lines of a file that never repeat

I need every ten lines to echo them into a div.

Example:

<div class='return-ed' id='1'>
line 1
line 2
...
line 9
line 10
</div>

<!-- next group of lines -->

<div class='return-ed' id='2'>
line 11
line 12
...
line 19
line 20
</div>

Does anyone know a way to do this?

an array from a file (), therefore its strings from a file.

+3
source share
4 answers

This should work:

$blocks = array_chunk(file('path/to/file'), 10);
foreach($blocks as $number => $block) {
    printf('<div id="%d">%s</div>', 
            $number+1, 
            implode('<br/>', $block));
}

Literature:

+3
source
echo '<div class="return-ed" id="1">';
$lineNum = 0;
foreach ($lines as $line) {
    if ($lineNum && !($lineNum % 10)) {
        echo '</div><div class="return-ed" id="'.($lineNum/10+1).'">';
    }
    echo $line."<br />";
    $lineNum++;
}
echo "</div>";
+1
source

google:

http://www.w3schools.com/php/php_file.asp

fgets() .

. .

Example from W3 Schools:

Example below

reads the file line by line until the end of the file is reached:

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>

All you have to do is have a count variable that counts up to 10 within the while loop. as soon as he reaches 10, do what you need to do.

0
source

Assuming your strings are in an array that you echoed, something like this would work:

$count = 0;
$div = 1;
foreach($lines as $line){ //or a for loop, whatever you're using
  if(0 == $count){
    echo "<div id='$div'>";
  }

  $count++;
  echo $line;

  if(10 == $count){
    echo "</div>";
    $count = 0;
  }
}
0
source

Source: https://habr.com/ru/post/1769562/


All Articles