JeroenMulder.com, Skip Navigation


Current Location: / Weblog

Recent Entries

PHP: single and double quotes

Tuesday / 19 April 05

I don’t write about PHP very often — this is the first time since the launch one year ago. However, I do quite a lot of work with PHP and relational databases such as MySQL. Almost every single time I review someone else’s work a common error related to using strings in PHP is made. Misunderstanding the way of defining strings in PHP is often the cause of many hours of debugging as well. If you are relatively new to programming and PHP you’ll most likely recognize this situation.

PHP lets you define strings using single quote, double quotes or heredoc. There’s a crucial difference between the first two and for some reason many people new to PHP start using double quotes. Hopefully the following explanation will save a couple of hours debugging for the starters among us.

The most important difference between the two is that a string enclosed in double quotes is parsed by PHP. This means that any variable in it will be expanded.

echo $var; // Results in the value of $var being printed
echo '$var'; // Results in the word '$var'
echo "$var"; // Results in the value of $var being printed

This means that concatenating strings can be done in two different ways as well.

$var = 'Ipsum';

echo 'Lorem ' . $var; // Results in 'Lorem Ipsum'
echo "Lorem $var"; // Results in 'Loren Ipsum'

This possibly isn’t anything new to you, but if you are working with HTML you can output valid markup while keeping your code readable. Using double quotes in a string enclosed with single quotes requires no escaping and vica versa. Using a double quote in a string enclosed in double quotes (idem for single quotes) does require escaping, which —in my opinion— degrades readability tremendously.

$text = 'Lorem Ipsum';
$uri = 'http://www.lipsum.com';

echo '<a href="' . $uri . '">' . $text . '</a>';
echo "<a href=\"$uri\">$text</a>";

Personally, I always stick to using single quotes and the dot syntax to concatenate strings, unless I need special characters such as new lines. Whatever you use is up to you, but hopefully this heads-up cleared a lot of confusion and puts an end to unreadible code and markup using single quotes.

Comments

1Dom posted:

19 April 05, 14:16:37 PM

That last example, with the link - why would you do this instead of just type it in normally?

Thank you for this article, it has helped me improve my knowledge somewhat, but PHP is all still a blur :)

Ah well, one step at a time. Let me master XHTML/CSS first :)

Take care, Dominic

2Tom posted:

19 April 05, 18:25:53 PM

Nobody really ever told me about ' '. I would spend hours escaping oodles of strings untill I saw this one example.

Stuff like this needs to be on page 1 of programming books. Everyone can code, but few can code well.

3Jeroen Mulder posted:

20 April 05, 02:18:14 AM

Dom, it's just an example. :-)

4Dom posted:

20 April 05, 11:40:26 AM

Jeroen - could've thought up something more useful! ;) :Þ

5Faruk Ates posted:

21 April 05, 18:03:34 PM

MySQL isn't much of a relational database, y'know ;)

Also, using single quotes is indeed much better, but when . ' your ' . 'code' . ' sta' . 'rts' . ' to ' . 'look' . like($this) . ' it\'s ' . 'time' . ' to ' . LOOK . $into . $other->approaches('to' . ' coding') . ' entirely'.

;)

6Richard Dunlop-Walters posted:

21 April 05, 19:08:56 PM

echo 'Lorem ' . $var; // Results in 'Lorem Ipsum'
echo "Lorem $var"; // Results in 'Loren Ipsum'

I appear to have spotted a typo. :o

7Jeroen Mulder posted:

22 April 05, 02:45:07 AM

Faruk, hehe, it isn't perfect, but in theory it is one. I suppose MySQL is a tiny bit too flexible compared to Sybase or PostgreSQL (which are the only ones I have worked with besides).

Rich, no you didn't. I'll edit it when I feel like editing it. ;-)

8Stephen Cameron posted:

23 April 05, 06:06:27 AM

Nice mini-tutorial Jeroen :-) I really don't visit you often enough...

I try not to mix HTML with PHP but when I do, I find that I quite like the heredoc option, except that it doesn't work unless the closing delimiter is at the very beginning of a new line - that's annoying because it messes with my nice indentation :-p I usually only use heredoc for messy stuff like HTML with javascript in it because you end up with both types of quotes in the string...

The dot delimiting method works well most of the time but when I have quite a lot of variables, I use double quotes and curly brackets, like so:

echo "Hi there {$user->name}, you last visited at {$data['visit']} and your favourite colour is {$user->favcolour}.";

That's a pretty lame example but the curly brackets can be useful for working with arrays... If you use objects, you don't need to use the curly brackets unless you have it right up against other alphanumeric characters.

I probably would use double quotes with variables in them a lot more if I knew it was ok to use single quotes for HTML (ie. <img src='$var' ...) but I remember reading that not all browsers like that.

9Faruk Ates posted:

24 April 05, 09:29:03 AM

Jeroen,

"I suppose MySQL is a tiny bit too flexible compared to Sybase or PostgreSQL"

Surely you mean too INflexible? :)

And also, a definition of an RDBMS is that it has full transaction support, which MySQL still doesn't have, natively.

10Kevin posted:

25 April 05, 05:19:26 AM

Not to mention... using " " where not needed, is just wasting processing, potentially even slowing down your website, if it's as big as say deviantART =P, since PHP has to try to parse something that does not need parsing...

I totally agree with you. I've also spent hours converting these types of little things in various pieces of code I've worked on.

I often use what Stephen sugested as well, but usually only in query strings. I'd be lying if I said I'd never used it anywhere else. It's very useful in cases where you have a lot of variables (as Stephen pointed out).

Hope all is well :)

11Mathias Bynens posted:

27 April 05, 15:02:57 PM

Using single quotes where possible results in nominally faster execution, but we're talking fractions of milliseconds. [ http://digital-web.com/articles/php_for_designers/ ]

12Tim posted:

27 May 05, 05:45:38 AM

Thank you for you help on this Jeroen,

After afew calculations and tidying up the way my pages are parsed, I knocked off about 20% parsing time :-)

13Andrew posted:

09 December 05, 21:23:26 PM

That's fantastic! I still echo a heap of html in my php outputs; this should save my hours and also really help to clean up my code.

Previously I've been using double-quotes (and escaping the html) AND the dot syntax for variables; will be great to move over to singles and leave the html alone!

14Alan posted:

09 January 06, 01:26:43 AM

PHP has always been a mistery for me. But you lit some shine on that. Thank you.

15Andreas posted:

22 June 06, 14:34:55 PM

I also prefere single quotes. Missed escapes can lead to a real mess and all the backslashes make code unreadable, IMO. The only thing I miss in single quotes is to include single quotes in the text. In Delphi I just need to write 'that''s' (two single quotes in a strean lead do not end the string , but represent a single quote. Well at least I have not found this in PHP, yet.

16Jeroen Mulder posted:

23 June 06, 05:52:27 AM

Andreas, as with double quotes, you can escape single quotes in a string enclosed in single quotes as well. I agree that backlashes make it unreadable, but in a rare occassion I use it.

echo 'Hi, how are you? I\'m fine.'; // Single quotes
echo "Hi, how are you? I'm fine."; // Double quotes

Depending on the situation I might deviate and opt to use double quotes instead.

17Kenneth posted:

23 June 06, 09:45:45 AM

I just spent Too Long(tm) discovering this:

'Here\'s my folder... C:\folder'
= Here's my folder... C:\folder

'Here\'s my printer... \\network\printer'
= Here's my printer... \network\printer

Did you notice that? \\network becomes \network!

\ escapes ' inside single quoted strings _and_ escapes itself for some crazy reason!

\' inside ' ' becomes: '
\\ inside ' ' becomes: \ << huh?
\anything else inside ' ' becomes: \anything else

Does this Not Make Sense(tm) to anyone other than me?

18Soeren posted:

10 August 06, 05:31:22 AM

Kenneth, it does make sense because the backslash is the character used for escaping - meaning it makes the next following character lose its special meaning.

Since the backslash itself is a special character you need to escape it to use it as a regular character. Thus, "\\" becomes "\".

> \anything else inside ' ' becomes: \anything else
That is intended behavior because special character sequences like \t, \r and \n (tab, CR and LF) need to be parsed by PHP to be turned into the corresponding control characters. That's why '\n' stays "\n" whereas "\n" turns into a single char with ASCII code 10.

To demonstrate my point imagine "\\n". It'll be parsed by PHP and as the first char encountered is the escape thar, the following char loses its meaning - which is the second backslash. With that, "\\n" becomes "\n" after parsing.

I hope that cleared things up a bit.
On the topic itself: I personally don't like using single quotes mixed with variables because all the single quotes make things look too chopped up as Faruk pointed out. I don't find escaping double quotes limiting readability much at all, as long as JavaScript doesn't get involved.

19RedNeck Newb posted:

19 November 07, 20:54:20 PM

Thanks for clearing up the confusion. I'm just starting to dabble in PHP.

Actually, your examples were just fine.

20narciss posted:

08 January 08, 11:49:19 AM

Hi.
Do you know what I should do if the string that's to be "echo"ed contains double quotes and single quotes? I want my code to echo the whole thing, but the point is that the string comes from input file, and so I can not use \" and \'

Is there a way to tell echo to interpret everything as simple text?

21Norzi posted:

28 January 08, 19:53:15 PM

hi..
anyone know how to echo email like this 'norzihana@mtdc.com.my' ? The coding is like below:

$query="Select Email from ComplEmail where Active='Y' ";
$result=mysql_query($query);
if (mysql_num_rows($result)>0)
{
$i=0;
while($row = mysql_fetch_array($result))
{
$i++;
$to .= ' ' . $row['Email'] . ',';
}
}

// Send Email to TIM's Staff
$to = substr($to,0,strlen($to)-1);
echo $to;

22jim posted:

31 January 08, 15:39:11 PM

Hi,

Very interesting stuff.

Here's another one for you.... I have a form which allows users to input things, including a name for their folder/team - Works fine.

I then pull a list of all folders for the DB and try to create a link for each folder name (allowing users to drill deeper) - Works fine.

The problem occurs when someone calls their folder something like tom's folder - understandable

here's the code I use to build the link

echo "<a href='show_color.php?selected=$customers_team_name'>";

here's what it produces

http://show_color.php?selected=tom

it should produce
http://show_color.php?selected=tom's folder

it stops at the single quote contained in the field, so the link fails as there is no entry for tom in the database

any ideas folks?

Thanks

23varney posted:

07 March 08, 11:14:41 AM

For post 22 above (Jim):

I'm not sure if I understand how you get the data from the database (so I am not sure how the database would store "tom's folder" for example, and what would be returned when you try to fetch it).
I think the problem is either to do with the ' in "tom's" - as in this case, the php parses the data up to the end of the string, and stops at ', where ' is the end of the string according to how php sees it.
Or perhaps you should try enveloping the whole string in one, e.g. "tom\'s folder". Not sure if you would need the backslash before the apostrophe.

The other thing you could try is to convert the spaces and apostrophe to url format code, using urlencode(). So it should say something along the lines of
http://show_color.php?selected=tom%27s+folder - hope this helps.

24Heather posted:

15 March 08, 11:58:55 AM

THANK YOU for this clarification. I too am very new to PHP and I've been struggling over a form. Your clarification of how and when to use single and double quotes will definitely help!

25skaterplus posted:

19 March 08, 15:31:36 PM

All this business is actually available in any good PHP manual. Just read it.
What is not present are a couple of other things. which might need a discussion.
It is all about escaping what you do not want to happen.

There are special functions to escape HTML code.
There are special functions to escape SQL code.
There are special functions to escape almost everything but the simple
problem: I just want to echo/print a string, which is not HTML code,
not SQL code and eventually not any code. Technically
I want to use the HTML code: value="<?php echo $var?>".
If $var happen to contain double quote stuff I mess up the HTML page.
If indeed the double quote is important for my data, I do not want to use
any standard escape tool too. I do not want $var=:"a" being the same
as $var=:a. I need the double quote to be present.
By the way check what happen if you use $var as "a". In the given
few chars code. The value is always a null string. It does render
as: value="""a". The extra "a" is just obviously ignored.

The problem is not a PHP problem at the beginning.
You know that you are allowed to write: href="pippo"
and that href=pippo will work too.

Ok maybe I am going to far away, but it woud be nice
to have a quote HTML name function, quote_html_ref()
to be used as:

value="<?php echo quote_html_ref($var)?>".

Where I will be sure that, beside HTML escape stuff, beside SQL stuff,
I can include my string in a standard HTML name.

This whole problem is generated by misunderstanding
between HTML quoting, PHP quoting, MySQL quoting. and so on.
I guess that any normal person can read a PHP manual,
Also the same person can read an HTML manual (This
side is difficult, in particular if you want to present a modern
HTML page). The difficult part is to bring the stuff together.
But being PHP a dedicated tool for HTML pages:
Why not make it simple?
Why not making <?php echo value=html_entity($pippo)?>
a standard function?

26Jeroen Mulder posted:

24 March 08, 04:59:00 AM

skaterplus, the reason I wrote this article is exactly because this information is not easily found in the PHP manual. It's there and it's well explained, but when you're learning PHP it's not a page that is often referenced or mentioned.

Anyway, regarding your question, the PHP function you're looking for is called htmlspecialchars() -- http://www.php.net/htmlspecialchars

This functions translated any single quotes, double quotes, sharp brackets or ampersands to their respective HTML entities, so you can easily write them as plain text as part of, say, an attribute in your HTML.

Post Your Comment






Comment Guidelines:
Please keep your comments relevant. Abusive, inappropriate and anonymous may be edited or removed, if deemed necessary.

Privacy Note:
Your e-mail address will never be displayed in public or forwarded to third-party organisations and is only stored for security reasons.


Recent Entries

Blogging Friends