Community Pick: Many members of our community have endorsed this article.
Editor's Choice: This article has been selected by our editors as an exceptional contribution.

Quotation Marks in PHP

Using Quotation Marks in PHP
This question seems to come up a lot for developers who are new to PHP.  And it got me thinking, "How can we explain the rules for quotation marks?"  For better or worse, PHP has so many rules!  This article tries to answer the questions.

First, some mandatory reading.  You need to understand the terms "variable" and "string" as they are used in the context of computer programming.  Take a moment to read these pages.  If it doesn't all "click" at first, don't be too concerned.  We will show some examples and explanation below.

Quotation Marks Used With Strings
A string is nothing more than a few characters strung together.  The code snippet below has examples of perfectly valid strings.  The first string is the single capital letter "A" and it has a length of one character.  The second string is the empty string.  It has a length of zero.  You can probably figure out the lengths of the other two strings.
                      Alphabet Soup

Open in new window

If you want to assign these literal string values to PHP variables, you must put quotes around them in the assignment statement.  Both of these examples are acceptable.  Note that one uses single quotes and the other uses double quotes.

$x = 'Alphabet Soup';
                      $y = "Alphabet Soup";

Open in new window

When you use variables (as opposed to literal strings) in PHP, there are different meanings for single and double quotes.  Double quotes allow variable substitution; single quotes do not.  This code example is functionally identical to the immediate prior example.  First, Alphabet Soup is assigned to $x, then $x is assigned to $y.

$x = 'Alphabet Soup';
                      $y = "$x";

Open in new window

Since there is no mix of literal string values and variable values, PHP will also allow you to write this without any quotes.  This is the preferred way to write the expression; avoid unnecessary quotes.
$x = 'Alphabet Soup';
                      $y = $x;

Open in new window

When you want an assignment statement to mix literal strings with PHP variables, you must use double quotes.  After this has been executed, the contents of $y is "Alphabet Soup for lunch."  

$x = 'Alphabet Soup';
                      $y = "$x for lunch";

Open in new window

But what if we had used single quotes? In the example below $y variable would contain "$x for lunch."  When single quotes are used, no variable substitution is performed.

$x = 'Alphabet Soup';
                      $y = '$x for lunch';

Open in new window

You can also use string concatenation, like this:
$x = 'Alphabet Soup';
                      $y = $x . ' for lunch';

Open in new window

Intermixed Quotes
PHP allows you to mix quotes and apostrophes in certain data structures, one of the most useful being the SQL query string.  You use the double quotes for the outermost wrapper and single quotes around the variables that are injected into the query.  See also When Quotes or Apostrophes are Part of the Data, below.
$nom = 'Ray';
                      $sql = "SELECT id FROM myTable WHERE name='$nom' LIMIT 1";

Open in new window

Quotes can become part of a variable if you assign them correctly.  Both of these statements are syntactically correct.  The first assigns a double quote to the $x variable.  The second assigns a single quote (apostrophe).
$x = '"';
                      $x = "'";

Open in new window

When quotes are misapplied, PHP will throw a parse error.  The PHP parser expects the single quoted string that starts with SELECT to end at the equal sign, but it finds extraneous data after the matching single quote.
                      $sql = 'SELECT id FROM myTable WHERE name='Ray' LIMIT 1';
                      // OUTPUTS: Parse error: syntax error, unexpected 'Ray' (T_STRING) in /path/to/script.php on line 2

Open in new window

Double Quotes Provide More Than Just Variable Substitution
When a string is enclosed in double-quotes PHP will interpret escape sequences for certain special characters that are prefixed by the backslash.  For example, you can embed tab characters by using \t and you can insert Unix end-of-line characters by using \n.  (But there is a better way of inserting end-of-line characters: use the predefined and context aware constant, PHP_EOL instead.  PHP knows what end-of-line sequence is appropriate for the OS and working environment.)

Quotation Marks Used With Other Variable Types
Quotation marks are not necessary or appropriate with other variable types, such as arrays, objects, integers, etc.  Just don't do that!  Advanced users: Learn about the magic method __toString().

Avoid Unnecessary Quotation Marks
If quotation marks are not necessary, do not use them.  Unnecessary quotes lead to fiddly punctuation and hard-to-find parse errors that waste your time.

Avoid Unnecessary Quotation Marks
Undoubtedly someone will ignore the advice to avoid unnecessary quote marks.  When you do that, you will need to use curly brackets around your substrings.  This fiddly punctuation is very easy to get wrong, resulting in parse errors.  That's why we try to avoid it.  Here is what the site says about this syntax:  "Complex (curly) syntax... This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions. Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognized when the $ immediately follows the {. Use {\$ to get a literal {$."

                      $arr = array('X' => 'Thing');
                      // FAILS: Parse error: syntax error, unexpected T_ENCAPSED...
                      $str = "In our array, 'X' points to the $arr['X']";
                      // WORKS
                      $str = "In our array, 'X' points to the {$arr['X']}";
                      $pointer = 'X';
                      $str = "In our array, we find the $arr[$pointer]";

Open in new window

Quotation Marks Used With Constants
PHP constants should be wrapped in quotation marks when they are defined with the define() function.  Since there is no variable substitution involved, single quote marks are appropriate, and double quote marks are OK. too.  Constants that are defined by the PHP function are different from class constants that are created by the const statement.

Whether define() or const were used to create a constant, it's important to remember that PHP constants are always used without quotation marks.

Quotation Marks Cause Type Coercion
The string "35" is not the same value as the integer 35.  They are different data types.  The string occupies two bytes and provides a character representation.  The integer provides the numeric value.  Many programming languages make a distinction between these two different types of data.  But PHP will usually permit these two data elements to be used interchangeably.  Run this script to see the effect as PHP changes the variable types.  On line 2, we assign an integer value to $x.  On line 4, PHP will change the data from integer to string as it is assigned to $y.  And on line 6, $y will be used as if it is an integer.
                      $x = 35;
                      $y = "$x";
                      $z = $y + 1;

Open in new window

Duck Typing in PHP
PHP is a loosely typed language.  The PHP engine attempts to cover up the complexity of the concept of a variable that can be any type by providing a uniform and intuitive set of rules that allow type conversion.  What that means is that PHP will make its own decisions about data types, based on the context in which the data is used.  You have some, but not complete control over this.  If it looks like a duck and quacks like a duck, PHP calls it a duck.  Whether the original data was an integer or a string is often unimportant to PHP.

Required reading, with plenty of examples, here:

Missing Quotation Marks Cause Time-Bombs
Here is something that looks OK but will get you fired from any professional programming job.
                      $x = array( 'a' => 1, 'b' => 2);
                      $y = $x[a];

Open in new window

The reason this is wrong, but permitted by PHP, goes to the ancient history of PHP, when it was called "Personal Home Page."  The authors wanted it to be a very easy language to use, and they thought that structured syntax was the source of difficulty in learning programming languages.  So in an effort to be forgiving and permissive they included all kinds of fall-back definitions, creating a cascade of meanings.  After running that little script, what is the value of $y?  The answer is, "You cannot really know!"  This happens because PHP will first try to use a as a constant.  If a is found, the constant value will be used as the index into the $x array.  If a is not found among the constants, PHP will raise a Notice and will pretend that you had put single quotes around 'a' and will retry the variable assignment.  But here's the gotcha: In the standard installation of PHP, Notice-level messages are suppressed, so you will never be told what PHP is doing to your array index!  The ambiguity will lie, latent, in your code for a long time.  Maybe, seemingly, forever.  Then one day, another programmer will need to work on the project, maybe in a different function or class, and she will define() the constant a.  At this point it will hit the fan, because like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope.  And without scope encapsulation, the constant is now injected into your programming.

Now, suddenly and without notice, a and 'a' have different meanings, and your script begins to fail.  Use quotes or apostrophes when they are needed.

When Quotes or Apostrophes are Part of the Data (SQL Queries)
You can embed quotation marks in quoted strings or single-quotes in single-quoted strings by escaping the quotes.  The term escape in this context refers to marking the quote or apostrophe in a way that removes its common meaning as a delimiter and permits it to become part of the string data.  The most common way of escaping quote marks is to put the backslash \ immediately before the character you want to escape.  In this code snippet the first line causes a PHP parse error, but the second line creates a string variable containing the name.  The third line creates the same string variable.

$x = 'O'Brien';
                      $x = 'O\'Brien';
                      $x = "O'Brien";

Open in new window

A practical application of the escape concept is used in SQL query strings.  These are typically constructed from double quoted strings, to allow for variable substitution so that data can be injected into the query.  The SQL engine expects string data to be enclosed in single quote marks.  Consider the following sequence to see why a backslash escape is needed.
                      $uname = "O'Brien";
                      $query = "SELECT id FROM myTable WHERE name='$uname' LIMIT 1";
                       * SELECT id FROM myTable WHERE name='O'Brien' LIMIT 1
                      // USING MySQLi::Real_Escape_String()
                      $Ename = $mysqli->real_escape_string($uname);
                      $query = "SELECT id FROM myTable WHERE name='$Ename' LIMIT 1";
                       * SELECT id FROM myTable WHERE name='O\'Brien' LIMIT 1

Open in new window

Advanced users: See also the use of escape sequences in regular expressions.

When Quotes or Apostrophes are Part of the Data (HEREDOC notation)
You can embed quotation marks in PHP strings with heredoc notation.  This is incredibly powerful and useful for many reasons, the foremost being variable substitution in templates.  You can write a PHP script that sets its variables, then assigns a string with heredoc notation, and all of the variables can be automatically substituted into the string.  If the heredoc string is a complete or partial HTML document, you can avoid most of the fiddly punctuation.  Here is an example showing how easy it can be:

<?php // demo/heredoc.php
                       * Demonstrate PHP heredoc notation
                      $date = date('c');
                      $text = <<<EOD
                      This is a bit of HTML text
                      It's got the apostrophe
                      It's got "double quotes"
                      It's also got <b>HTML Markup</b>
                      It's got \t\t tab characters
                      It embeds the ISO-8601 standard date/time here: $date
                      All of this is easy, with no special escape characters because the text is wrapped in HEREDOC notation.
                      Pretty cool, eh!
                      // SHOW THE WORK PRODUCT
                      echo '<pre>';
                      echo $text;

Open in new window

Quotes and Apostrophes in HTML Output
As a matter of client security, a script should never echo unfiltered data directly to the client browser (malicious JavaScript is the obvious danger).  Instead it's correct to use htmlspecialchars() on any character string that you want to embed in HTML.  HtmlSpecialChars() makes appropriate and safe translations of the characters with special meanings, such as quotes, wickets like < or > and the ampersand.  The resulting string can be displayed but cannot affect the browser or invoke JavaScript.  This function has application in XML documents, too.

Quotes that Look like Quotes but are Not Really Quotes
Have a close look at the next code snippet.  Can you see the different kinds of quotation marks?  Your browser may render these differently enough that you will be able to tell them apart, or it may not.  The quotation marks around the $user variable value are not the standard keyboard quote marks.  Instead they are something that was probably copied from Word for Windows or a similar text editor.  PHP does not recognize them as quote marks and instead tries to use them as part of the variable assignment for $user.  Needless to say this will not work out well!  But PHP will only throw a Notice message.  If you do not have error_reporting(E_ALL) set, you will not see the Notice message and the script will fail, perhaps without any useful error message.  Executive summary: Check your quote marks very carefully -- especially if you copy and paste using a text editor.  One quote from an EE member on this topic: "I found in textedit (Mac's version of notepad) you have to turn off substitutions / smart quotes."

$host = "localhost";
                      $user = “webapp”;
                      $pass = "abcxyz"; 

Open in new window

Read the man page links in this article, and make sure you understand them.  Use var_dump() to check the type and contents of your variables.  And post new questions here at EE if you're not 100% sure what PHP is doing to your data!

If you're new to PHP, this article has some good "getting started" guidance, with links to vetted learning resources that teach the essentials of the PHP language.

Please give us your feedback!
If you found this article helpful, please click the "thumb's up" button below. Doing so lets the E-E community know what is valuable for E-E members and helps provide direction for future articles.  If you have questions or comments, please add them.  Thanks!

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.