Don’t Quote Me On That

8/18/2010 9:30 AM By

Let’s examine one of the best practices for writing PHP: what quotes to use. This may seem like a strange thing to consider, but just come along, gentle reader, and all will be made clear. Let’s take this example PHP:

<?php echo "http://www.artisantalent.com/"; ?> 

This can be rendered identically like so:

<?php echo 'http://www.artisantalent.com/'; ?> 

So what’s the big deal? Let’s look at a more complex example. Here it is with double quotes:

<?php echo "<a href=\"http://www.artisantalent.com/\" title=\"Artisan Talent\">"; ?>

Wait… what just happened? Well, we needed to use double quotes for the HTML we were echoing, and because of that, we needed to escape the double quotes that don’t actually end the string by using a backslash. “Well, why not use single quotes for the HTML?” you might ask, and that would be because it’s considered best practice to use double quotes for HTML. Not only that, but if you’ve already gotten in the habit of using double quotes for your HTML, having to relearn that behavior or adjust all of your existing HTML is just a pain.
Now let’s look at that PHP code snippet using single quotes for the string:

<?php echo '<a href="http://www.artisantalent.com/" title="Artisan Talent">'; ?> 

How much nicer this is! Not only is that easier to write, but it actually processes faster in some cases, meaning your PHP doesn’t work as hard. And that’s a Good Thing.

One caveat: if you want to use the special formatting characters (\n for new line, \t for tab, etc.), you’ll need to encase those in double quotes, as they’ll be parsed literally within single quotes (since single quotes ignore the backslash escaping character). So you’d want to do this:

<?php echo "\t\t".'<a href="http://www.artisantalent.com/" title="Artisan Talent">This link would be indented by two tabs' ?> 

And there you have it, best practice with single quotes.

Tags:

Comments are closed.