3

Simple question. I have an array of 21 elements, and show every three of them inside a <div> block. The code is something like this:

<?php
$faces= array(
  1 => 'happy',
  2 => 'sad',
  (sic)
  21 => 'angry'
);

$i = 1;
foreach ($faces as $face) {
  echo $face;
  $i++;
}

?>

The problem lies when this array doesn't have 21 elements, sometimes it gets 24, an other times 17. How I wrap every three of them, and wrap alone the rest? I came up with using switch and case, but that works only when there are 21 elements only. I think I could count them beforehand and put a closing in the last one (even if it is a group of one element).

Community
  • 1
  • 1
DarkGhostHunter
  • 1,521
  • 3
  • 12
  • 23

3 Answers3

4

You already have most of it here. All you're missing is something to test if you're ready to wrap. So before you increment $i, try:

$i = 1;

foreach ($faces as $face)
{
    echo $face;

    if ($i % 3 == 0)
    {
        echo "<br />"; // or some other wrapping thing
    }
    $i++;
}

This will ensure you're wrapping every 3 faces, leaving any remainder in the final unit.

Jimmy Sawczuk
  • 13,488
  • 7
  • 46
  • 60
  • You would also need `else` for non-wrapping – Blaster Jun 29 '12 at 21:07
  • I don't think so. Wraps are an action, if you don't wrap you're basically doing something normally. You shouldn't need to do anything unless you have to wrap (unless you design your code that way). – Jimmy Sawczuk Jun 29 '12 at 21:09
  • 1
    Ah you are right, probably need to sleep now, it is too late 2:30AM, +1 though. – Blaster Jun 29 '12 at 21:10
2
print '<div>';
$i = 1;
foreach ($faces as $face) {
  if ($i % 3 == 0) print '</div><div>';
  echo $face;
  $i++;
}
print '</div>';
Māris Kiseļovs
  • 16,957
  • 5
  • 41
  • 48
1

I would use array_chunk. You can split the array into a multi-dimensional array in groups of three. If the number of elements is not a multiple of three, the last element will contain all of the remaining child elements, however many they may be.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 1
    +1 Surprised that it didn't get upvoted, especially since the OP required a follow up question to fully satisfy his answer; using array_chunk first may have taken enough complexity out of the question for him to solve it by himself ;-) – Ja͢ck Jul 01 '12 at 07:20