Formatting a string with optional elements
I’ve often found myself writing little bits of code to format strings with optional elements. The classic example is outputting the company someone works for, together with their position in that company—if the position is given. The format if both are given is:
[position], [company]
If the position isn’t given, you just output the company. Without, obviously, the comma. It’s a trivial thing to code, but on a current project I’ve found myself doing it in several different places. Of course, this suggests there should be a function written for it.
Ideally the function should be able to cope with any number of optional elements. With PHP’s func_get_args(), it’s easy:
function formatOptionalText( $delimiter ) {
$elements = array_slice( func_get_args(), 1 );
$text = "";
$i = 0;
foreach ( $elements as $element ) {
if ( trim ( $element ) ) {
if ( $i && $text ) $text .= $delimiter;
$text .= $element;
}
$i++;
}
return $text;
}
Note that you have to pass a delimiter first, and you should include a space if necessary (e.g. ", "). After that, pass any number of strings and they’ll be output without gaps.
Welcome! I build websites - mostly based on the brilliant, free & open 
Oren Yomtov (21st November 2009)
Thanks for the code. It’s very handy.