Yep. I don't often use ternary operators, but when I do, they're often in (s)printf() statements. 🙂
You could be even more functional and move those operations into a function, and then just call it, for even DRYer code.
function classIfSet($class)
{
$result = '';
if(!empty($class)) {
$result = ' class="'.htmlspecialchars(trim($class)).'"';
}
return $result;
}
function ULOut(array $data, $listClass=null, $itemClass=null)
{
printf(
"<ul%s>\n",
classIfSet($listClass)
);
foreach($data as $item) {
printf(
"<li%s>%s</li>\n",
classIfSet($itemClass),
htmlspecialchars($item)
);
}
echo "</ul>\n";
}
Code...refactor...repeat. 🙂