How can I “catch” every seventh element in the list?

I am using DirectoryIterator to display files. In this scenario, my directory contains 19 files.

I need to create a list that wraps 7 files in <div>.

I have to get tired because I cannot complete this simple task.

My code has been updated to display the sentences below :

$i = 0;
echo '<div class="first_div">';

foreach ($dir as $fileinfo) {
  if ($fileinfo->isFile()) {
    if(($i % 7 == 0) && ($i > 0) )
      echo '</div><div>';

    echo 'My file';
    $i++;
  }
}
echo '</div>';

Any help could be fixed.

+3
source share
8 answers

Try using the mod (%) operator to determine if the current file number is seventh:

echo "<div>";
$i = 0;
foreach ($dir as $fileinfo) {
   // Remainder is 0, so its the first of 7 files. 
   // Skip this for the first one, or we'll get a blank div to start with
   if($i % 7 == 0 && $i>0) echo "</div><div>";
   echo $filenamehere;
   $i++;
}
echo "</div>";

(Code not verified, but should work)

EDIT: $i, , , 2, 0, .

+2

- :

echo '<div>';

$i = 0;
foreach ($dir as $fileinfo) {
   if($i % 7 == 0 && $i != 0) {
       echo '</div><div>';
   }
   // do stuff
   $i++;
}

echo '</div>';
+7

or ssomething like

$chunk_size = 7;
foreach (array_chunk($dir, $chunk_size) as $chunk) {
   echo '<div>';
   foreach ($chunk as $fileinfo) {
      // echo list item $fileinfo here
   }
   echo '</div>';
}
+3
source

The mapping is similar to this:

$c = 0;
foreach ($files as $file) {
  echo $file;
  if ($c % 7 == 0) {
    //7th file
  }
  $c++;
}
+1
source

Using mod 7

$counter += 1;
if($counter % 7 = 0)
    //New div

Doesn't match the 100% syntax for this I am php, but ther should be some

+1
source

You can use array_chunk () to split the array into pieces.

<?
$dir_chunks = array_chunk($dir, 7);

foreach($dir_chunks as $dir)
{
    echo '<div>';
    foreach ($dir as $fileinfo) {
      if ($fileinfo->isFile()) {
         // build list here
      }
    }
    echo '</div>';
}   
?>
+1
source

Or (throw operator% and add more SPL )

<?php
$path = '......';
$nrit = new NoRewindIterator(new DirectoryIterator($path));
while ( $nrit->valid() ) {
  echo "<div>\n";
  foreach( new LimitIterator($nrit, 0, 7) as $it ) {
    echo '  ', $it, "\n";
  }
  echo "</div>\n";
}
+1
source

Use this code:

if(($i-2) % 7 == 0)
0
source

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


All Articles