John the Painter John the Painter - 2 months ago 10
PHP Question

PHP modulos and items that don't equally divide

I have a simple foreach loop set up. I've set it up so there's a count

$count
and every four items it would insert an element containing information about the four items.

<?php if ($count%4 == 0) : ?>
<div></div>
<?php endif; ?>


but what if the total number of items don't equally divide by 4? What if there's 17 items? Is there a way to check what is left over?

Thanks.

Answer

So it depends what you're after really, you could do something as simple as this to put your 'Div' after the remaining elements if it didn't end on something that was modulus 4

$items = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven'];
$itemsCount = count($items);

for ($i = 0; $i < $itemsCount; ++$i) {
    echo $items[$i] . '<br/>';

    if (($i+1) % 4 === 0) {
        echo '---- Past four items explained here.<br/>';
    }
}

if ($itemsCount % 4 !== 0) {
    $x = $itemsCount % 4;
    echo '--- Past '. $x .' items explained here.<br/>';
}

Output:

One
Two
Three
Four
---- Past four items explained here.
Five
Six
Seven
--- Past 3 items explained here.

You could also chunk the array into smaller parts and do a nested loop.

$items   = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven'];
$chunked = array_chunk($items, 4);

foreach ($chunked as $group) {
    foreach ($group as $element) {
        echo $element . '<br/>';
    }
    echo '---- Information about the last group here.<br/>';
}

Output:

One
Two
Three
Four
---- Information about the last group here.
Five
Six
Seven
---- Information about the last group here.

If you just want to know how many you will have left over after you have split your content into chunks of 4 you can do the following:

$amountLeftOver = $arrayLength % 4;

Hope that helps.

Comments