tags:

views:

58

answers:

4

i need to, for every ten lines, echo them in 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 1
line 2
...
line 9
line 10
</div>

does anyone know a way to do this?

array is from file(), so its lines from a file.

A: 

With a quick google search:

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

Reading a File Line by Line

The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example from W3 Schools:

The example below

reads a file line by line, until the end of 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 need to do is have your counting variable that counts up to 10 within that while loop. once it hits 10, do what you need to do.

Ryan Ternier
+1  A: 
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>";
webbiedave
Using `%` is more elegant than mine, but missing the closing `<div>` for all but the last loop.
Tim Lytle
Yeah. I shouldn't type code right into textarea first thing in the morning. I've added the close div.
webbiedave
+1 for using `%` then.
Tim Lytle
Thanks Tim. –––
webbiedave
A: 

Assuming your lines are in an array that you're echoing, 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;
  }
}
Tim Lytle
I think you mean `foreach ($lines as $line)`
webbiedave
@webbiedave - Indeed. Looks like mornings are dangerous. Updated.
Tim Lytle
lol. ––––––––––
webbiedave
Er...I would have picked one of the other answers - not that I don't appreciate the 'accept'. Guess this one just makes the logic obvious?
Tim Lytle
+2  A: 

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));
}
Gordon
+1 for an interesting solution.
Tim Lytle
+1 for slickness.
webbiedave
well written, thanks.
tann98