Home » Php » php – How to insert <ul> in foreach loop every 10 records

php – How to insert <ul> in foreach loop every 10 records

Posted by: admin July 12, 2020 Leave a comment

Questions:
<?php foreach($products as $product) : ?>

<li><a href="<?php echo base_url(); ?>main/products/<?php echo $product->id; ?>">
<?php echo $product->name; ?> </a></li>

<?php endforeach; ?>

So the code above get’s all records in a DB and generates links. 100 Records in the table – I want to split the design into 5 col. So I will do that in CSS but I need to be able to enclose

<ul> on every 20 records</ul>

How can i count the loop and do this?

How to&Answers:

Do like this , this will solve your problem

 <?php 
 *$i = 0;*
 echo "<ul>";
 foreach($products as $product) : 
 if($i % 20 == 0) echo "</ul><ul>"; 
?>
<li><a href="<?php echo base_url(); ?>main/products/<?php echo $product->id; ?>">
<?php echo $product->name; ?> </a></li>
<?php 
 //if($i % 20 == 0) echo "</ul>";
 $i += 1;
 endforeach; 
 echo "</ul>";
 ?>

*edit- set $i = 0; since arrays count from [0] by setting it to [1] makes the first col have 19 instead of 20. By setting it to [0] Each col has 20. 🙂 Thanks again ~fabio

Answer:

This should work

<?php $products = array('1','2','3','4','5','6','8', 9, 10, 11, 12);?>
<?php $count = 0?>
<?php foreach($products as $product) : ?>
<?php $count = $count + 1; ?>
<?= (($count == 5) ? "<ul>" : '' )?>
<li><a href="<?php echo base_url(); ?>main/products/"></a></li>

<?= (($count == 5) ? "</ul>" : '')?>
<?php (($count == 5) ? $count = 0 : '' )?>
<?php endforeach; ?>

Answer:

 <?php 
     $i = 1;
     echo "<ul>";
     foreach($products as $product) : 
     if($i % 20 == 0) echo "</ul><ul>"; 
    ?>
    <li><a href="<?php echo base_url(); ?>main/products/<?php echo $product->id; ?>">
    <?php echo $product->name; ?> </a></li>
    <?php 
     $i += 1;
      endforeach; echo "</ul>"; ?>

Answer:

Checkout php’s array_slice method. It will allow you to slice the array into smaller arrays of 20 objects each.

Answer:

<?php    $i=0;
         echo "<ul>";
         foreach($products as $product) :
         if($i%8==0&&$i!=0) echo "</ul><ul>"; ?>

         <li>
          <a href="<?php echo base_url(); ?>main/products/<?php echo $product->id; ?>">
           <?php echo $product->name; ?>
          </a>
         </li>

<?php    $i+=1;
         endforeach;
         echo "</ul>"; ?>