1

I have an array containing information about some images, which I am using to print a number of img html tags by a foreach loop as follows:

<?php foreach ( $images as $image ) : ?>  
<img alt="<?php echo $image->alttext ?>" src="<?php echo $image->thumbnailURL ?>" />  
<?php endforeach; ?>

I would like to wrap a div around every 10 images. The remainder should get a div as well.

I am thinking I need to use array_chunkon $images and wrap the above in another loop for each chunk. The little bit of math I did to start is as follows:

$pics_per_page = 10;  
$imgcount = count($images);  
$num_pages = ceil($imgcount/$pics_per_page);  
$pages = array_chunk($images, $num_pages);

How do I proceed from here? How do I use the $images array correctly, if at all, in outputting my HTML?

Forgetting about the array_chunk method, I have the following way, but the array_chunk method seems cleaner.

for i from 1 to num_pages:  
    echo "<div>"  
        j = (i-1) * pics_per_page;  
        while j <= i * pics_per_page  
            echo "<img src = "$images[j]->thumbnailURL />";  
        endwhile;   
    echo "</div>"  

2 Answers 2

3

You are using array_chunk [docs] wrongly. You just have to specify the size of each chunk:

$chunks = array_chunk($images, 10);

Then you need a nested for (foreach) loop:

<?php foreach($chunks as $chunk): ?>
    <div class="someClass">
    <?php foreach($chunk as $image): ?>  
        <img alt="<?php echo $image->alttext ?>" src="<?php echo $image->thumbnailURL ?>" />  
    <?php endforeach; ?>
   </div>
<?php endforeach; ?>
Sign up to request clarification or add additional context in comments.

Comments

2

You could use it without array_chunk too.

<?php
$imgTot = count($images);

echo '<div>';

for($i=0; $i<$imgTot; $i++)
{
    if ($i % 10 == 0) {
        echo '<div>';
    }

    echo '<img alt="'.$image->alttext.'" src="'.$image->thumbnailURL.'" />';

    if ($i % 10 == 9) {
        echo '</div>';
    }
}

echo '</div>';

?>

See the working example here: http://codepad.org/FkdTEH91

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.