A quick note about formatting strings

by Guillermo A. Fisher

I’m writ­ing this because I just saved 8 – 10 lines of code by using printf().

I know it’s pretty easy to rely on con­cate­na­tion to print strings, but lib­eral use of printf() and sprintf() can add clar­ity to your code and cut com­plex­ity. Take the fol­low­ing, for example:

$uri = "/images/example.jpg";
$title = 'This is an example image';
$class = 'thumbnail';

No big deal. Now, let’s use that infor­ma­tion to build and out­put an image tag:

echo '<img src="' . $uri . '" alt="' . $title . '" class="' . $class . '" />';

Is that espe­cially dif­fi­cult? No. But, if you’re like me, you got the quotes wrong the first time you wrote it and had to double-check your­self. That’s not exactly easy on the eyes, either. I guess, to get around the quote con­fu­sion you could do this:

echo "<img src="\$uri\" alt=\"$title\" class=\"$class\" />";

or this:

echo "<img src='$uri' alt='$title' class='$class' />";

The first option is cleaner, but still ugly… and I try to avoid mak­ing PHP fig­ure out what’s a vari­able and what isn’t. The sec­ond option isn’t all that bad, really, except that I hate using sin­gle quotes around HTML attrib­utes. Enter printf():

printf('<img src="%s" alt="%s" class="%s" />', $uri, $title, $class);

That pleases me.

Tagged as the following: .

Your Feedback Civil & constructive, please.

Leave a Reply