Search code examples
phpfor-loopforeachforeach-loop-container

Hello with a for loop with a nested foreach


I have the following php,

 <ul>
<?php $count = count($products); ?>
            <?php for($i=0; $i < $count; $i++ ): ?>
            <li>
                <?php foreach ($products as $k => $v) : ?>
                    <div>
                        <a href="">
                            <img src="<?php echo base_url(); ?>media/images/products/<?php echo $v['product_image_small']; ?>" alt="<?php echo $v['product_title']; ?>" rel="<?php echo $v['product_id']; ?>"/>
                        </a>
                    </div>
                <?php endforeach; ?>
           </li>
            <?php endfor; ?>
        </ul>

What I wanting to achieve is to create an li nested with up to 6 divs, and once there are 6 divs I want to create a new li. The code above is currently creating the following,

<li>  
<div></div>  
<div></div>  
<div></div>  
<div></div>  
</li>

...however there should only be 2 divs in my li due to the size of the products array.


Solution

  • You are looping 2 x 2 times, instead of 2, as both loops are nested. Use only for or foreach.

    To answer your real question: how about something like ...

    echo "<li>";
    for ($i = 0; $i < $count; $i++)
    {
       // ...
    
       if ($i % 6 == 5)
         echo "</li><li>";    
    }
    echo "</li>";