A quick note about formatting strings
by Guillermo A. FisherI’m writing this because I just saved 8 – 10 lines of code by using printf().
I know it’s pretty easy to rely on concatenation to print strings, but liberal use of printf() and sprintf() can add clarity to your code and cut complexity. Take the following, for example:
$uri = "/images/example.jpg"; $title = 'This is an example image'; $class = 'thumbnail';
No big deal. Now, let’s use that information to build and output an image tag:
echo '<img src="' . $uri . '" alt="' . $title . '" class="' . $class . '" />';
Is that especially difficult? No. But, if you’re like me, you got the quotes wrong the first time you wrote it and had to double-check yourself. That’s not exactly easy on the eyes, either. I guess, to get around the quote confusion 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 making PHP figure out what’s a variable and what isn’t. The second option isn’t all that bad, really, except that I hate using single quotes around HTML attributes. Enter printf():
printf('<img src="%s" alt="%s" class="%s" />', $uri, $title, $class);
That pleases me.
Your Feedback Civil & constructive, please.