在PHP中包含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).

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.

print '<div>';
$i = 1;
foreach ($faces as $face) {
  if ($i % 3 == 0) print '</div><div>';
  echo $face;
  $i++;
}
print '</div>';

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.