$counter = 0; foreach ($contactlist as $contact) { ++$counter; // output an image if (!$counter % 4) { // start a new row. } }
$contactlistrows = array_chunk($contactlist, 4); foreach ($contactlistrows as $row) { // start row foreach ($row as $cell) { // print cell } // finish row }