Skip to navigation | Skip to content



Archive for the category ‘miscellaneous’

Rushkoff on branding

I usually keep posting here strictly to the techie nitty-gritty. But I thought that aside from this talk by Douglas Rushkoff directly addressing important issues around commerce and the internet, it’s also just a fundamentally important perspective.
Read more »

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

This is my work blog, which I’ll mostly be using (initially at least) to document various tricks, tips, workarounds, hacks and other sundry discoveries I make doing web work.

I don’t expect it to be too busy. But when I solve a particularly tricky coding problem, or discover something tremendously useful, I find it a good practice to document it on the web—both for my own future reference and for other poor souls struggling with the same thing.

Comments will be closed because I don’t expect much here apart from spam! There’s always the contact form if you want to respond to something…

View complete archives »