Wrapping 3 objects or less inside a while / foreach in PHP

Posted by DarkGhostHunter on Stack Overflow See other posts from Stack Overflow or by DarkGhostHunter
Published on 2012-06-29T21:02:05Z Indexed on 2012/06/29 21:16 UTC
Read the original article Hit count: 179

Filed under:
|
|
|
|

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).

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays