Without going into the content of your code, I don't like the intermingling of HTML and PHP. Perhaps it's me? I would write your code something like this:
if ($count = $this->likes->count()) {
$visible = 12;
$hidden = $count > $visible ? $count - $visible : 0;
echo '<div class="likes_detail">'.PHP_EOL;
$r = 0;
foreach ($this->likes as $like) {
echo "<span>{$like->name}</span> ".PHP_EOL;
$r++;
if ($r >= $visible) break;
}
if ($count > $visible) {
echo '<span class="more_users">and '.$hidden.' more…</span>'.PHP_EOL;
}
echo '</div>'.PHP_EOL;
}
Now I probably would not use echo's all over the place, and I would explain my code in comments. Why $visible = 12;
for instance? It might be obvious to you, but I have not idea. Ah, there will be a maximum of 12 visible names! So, let's restructure this:
// set the maximum of names to display
$maxNames = 12;
// if there are any likes we display them
if ($total = $this->likes->count()) {
// get the maximum number names of likes, or less
foreach ($this->likes as $like) {
$names[] = $like->name;
if (count($names) == $maxNames) break;
}
// generate html output
echo '<div class="likes_detail"><span>'.implode('</span> <span>',$names).'</span>';
if ($total > $maxNames) {
echo '<span class="more_users">and '.($total-$maxNames).' more…</span>';
}
echo '</div>';
}
I've tried to seperate the processing of information from the HTML output, but since this is such a short piece of code, there's only so much I can do. Is this code part of a method in a class? Or is it just hanging out there somewhere in a HTML generating page? I use a HTML support class to create HTML. This prevents many common errors in HTML. The output section would look something like this:
// push likes names into html
$likesTag = $bodyTag->division('likes_detail');
foreach ($names as $name) $likesTag->span('',$name.' ');
if ($total > $maxNames) {
$likesTag->span('more_users','and '.($total-$maxNames).' more…');
}
This also means I don't have to worry about what is PHP and what is HTML, I can work in pure PHP. It makes for cleaner code, and fewer HTML errors.