The difference between double and single quotes in PHP. Php quotes, quotes single, double, shielding What are variables in single PHP quotes

Rows in PHP are framed by single or double quotes. The main difference is that in double quotes can be substituted with a variable:

Now we can come up with another solution to the task of the lesson variables in PHP:

$ title"; Echo"

$ Content
"; ?>

How does PHP find a variable in the string?

Everything is simple. Remember what characters can be used in the name of the variable? These are numbers, letters and emphasising _.

Here is PHP and accepts for the name everything is between the $ symbol and the first forbidden symbol.

In the following PHP code, it will incorrectly determine the name of the variable and give an error:

Result in the browser:

Notice: undefined Variable: Priceurb in D: \\ OpenServer \\ Domains \\ site \\ index.php on line 3

To PHP correctly determined the name of the variable in the string, you need to place it in curly brackets ():

Result in the browser:

1499rub

There is no unambiguous opinion, what quotes need to be used for ordinary lines in which nothing needs to be substituted. However, many programmers prefer to use single quotes.

The fact is that dual quotes from many cause the association "to this line should substitute something." Therefore, I recommend using single quotes for ordinary text, and double - only when you need to substitute the variable in the text. Example:

Shielding quotes

If you need to put quotes inside the string, there are 2 ways to do it:

In the second example, the reverse layer \\ shields the quotes next after it so that PHP perceived it as a string.

What do you think you need to do to display only the reverse slash? After all, it will shield a closing quotation. It's funny, but you need to write a second slash to shielding the first:

Tabulation and transfer of string in double quotes

The reverse layer in double quotes allows you to shield not only quotes and yourself, but also some other characters. The most popular of them is a tab (the long space that you get when you press Tab) and the transfer of the string. They look like this:

Write a script that:
1. Creates a $ Type variable with a game value.
2. Creates a variable $ Name with the "World of Warcraft" value (with quotes).
3. Displays both variables inside the tag

. There must be a space between the variables.

I am not an expert in PHP programming, but I'm a bit confused why I see some code in PHP with a string placed in single quotes, and sometimes in double quotes.

I just know Vet or C language, if it is in one quotion, it means that this is a symbol, not a string.

11 Responses

what you need to know

$ a \u003d "name"; $ B \u003d "MY $ A"; \u003d\u003d "My Name" $ \u200b\u200bC \u003d "My $ A"; ! \u003d "MY NAME"

in PHP, people use a single quotes for defining a constant string, for example "a", "My name", "ABC XYZ", when using double quotes to determine the line, contains an identifier, for example "A $ B $ C $ D".

Echo "My Name";

faster than

Echo "My Name";

Echo "My". $ a;

slower than

Echo "MY $ A";

this is true for other rows used.

an example of single, double, heredoc and noowdoc quotes

both types of nested characters are rows. One type of quotes is conveniently used to conclude a different type of quotation. "" "and" ". The greatest difference between the types of quotes is that references to nested identifiers are replaced inside double quotes, but not inside single quotes.

in PHP, the same quotes text is considered as a string value, and the dual quotation text will analyze variables, replacing and processing their value.

$ test \u003d "variable"; Echo "Hello Mr $ Test"; // The Output Would be: Hello Mr Variable Echo "Hello Mr $ Test"; // The Output Would be: Hello Mr $ Test

here, double quotation is analyzing the value, and single quotation is considered as a string value (without parsing a $ test variable.)

perhaps I'm a little late, and a little off topic, but still ...

you do not need to choose because of the contents of your row between:
Alert ("IT" S \\ "Game \\" Time "); or alert (" IT \\ "s" Game "Time.");

instead, you can enter like this, and then use double or single quotes, because it does not matter:
Alert ("IT's" Game "Time"); and Alert ("IT's" Game "Time");

$ Name \u003d "Test"; $ Singlequote \u003d "This is example for single quote $ name"; // HERE $ NAME VARIABLE NOT EVALUATING ECHO $ \u200b\u200bSINGLEQUOTE; // Output: This is example for Single QUOTE $ Name $ Singlequote \u003d "This is example for single quote $ name"; // HERE $ Name Variable Will Evaluate and Replace Variable Value Echo $ Singlequote; // Output: This is example for Single QUOTE TEST ALSO INSIDE SINGLE QUOTE EVALUAT FASTER CAMPARE TO DOUBLE QUOTES

one:

it is very important to note that the string with the closing identifier help hereOC. must contain any other characters except semicolon (;). This means that the identifier cannot be retreatand can not be premises or tabs before or after the comma.

example:

$ STR \u003d.<<

What kind of quotes use to design strings - apostrophes or classic double quotes?

Let's analyze the difference between double and single quotes in PHP, and on examples, find out when you need to use.

Variables and shielding sequences for special characters encountered in lines enclosed in single quotes are not processed. The lines framed by apostrophes are processed by the PHP interpreter much faster than similar lines surrounded by double quotes.

The reason here is simple: Lines in dual quotes Interpreter PHP additionally checks for variables and if these are located, then instead of the variable name in the string inserts its value. But the string concluded in the apostrophes is perceived by the interpreter as ordinary text and no transformations in these PHP lines does not conduct. I think it is clear that the processing of lines in single quotes in any case will occur faster.

To begin with, we describe how to determine the string, and then check how faster the rows in single quotes will occur.

The easiest way to determine the string is to conclude it into single quotes ("). In order to use single quotes inside the string enclosed in single quotes, they need to be ahead of the reverse deficent (\\) symbol, that is shielded. If the reverse sink Must go before a single quotation or being at the end of the line, you need to duplicate it. If you try to shield any other character, the reverse sinking feature will also be printed.

We give an example of using single quotes:
// Remove: Simple String
echo "Simple Row";
// Removes: i "M Here
echo "I \\" M Here ";
// Will out: it will not insert: \\ N new string
echo "It will not insert: \\ N new string";
// Will out: the $ sample variable will also not substitute
echo "$ Example variable will not substitute either"; If the string is enclosed in double quotes ("), PHP recognizes more control sequences for special characters and also substitutes instead of the variable name in the string of its value. Just as with single quotes, in order to use double quotes inside a string concluded. In double quotes, they must be ahead with a symbol of the reverse braid (\\).

Let us give an example of using double quotes:
// Remove: Simple String
echo "Simple Row";
// Will out: firm "Snowdrop" "
echo "Firm \\" Snowdrophry \\ "";
// Will out: it will translate to a new string
echo "It will translate to the new line \\ n";
// Will out: the variable will substitute
$ example \u003d "substitut";
echo "Variable $ Example"; It should also be remembered that the sequence "\\ n" (new line), "\\ r" (return carriage) for ordinary text, and not for HTML. So in the browser you will not see changes (only in the source page of the page).

Let's find out how faster than single quotes of double. For measurements, write a short test script, and immediately note that if you have it to test it, the results that depend on the hardware of your PC or server will be different.
// Return the time stamp at the beginning of the cycle
$ START \u003d Microtime (True);
// Create a cycle cycle for 1 million iterations
for ($ i \u003d 0; $ i< 1000000; $i++) {
$ Text \u003d "Here is a symbol string";
}
// Calculate the time spent
$ TIME \u003d (Microtime (True) - $ Start); Result: 0.09 seconds.

If we replace single quotes on double:
$ Text \u003d "Here is a symbol string"; The result will be equal to 0.10 seconds.

As we see, when using text lines, the difference in time of execution is very small, it can even be said and does not exist at all. The most interesting will begin when we try to combine the string and variable.
$ Text \u003d "Here is the symbol line $ i"; or
$ text \u003d $ i. "Here is a symbolic string"; The result is approximately: 0.27 seconds.

The difference is very sensitive. Concatenation and dual quotes clearly affect the speed if variables are added to the string.

When the server processes the code, it checks all the contents of dual quotes for variables, constants and other. It takes time. And the fact that there is between single quotes The server processes as the finished text and it does not care what is located there. The difference between the speed of single and double quotes is very insignificant, but if you develop a highly loaded project, somewhat saved milliseconds are already a victory.

String values \u200b\u200bare text strings (briefly row). A string is a sequence of zero or more characters. Symbols include letters, numbers, punctuation marks, special characters and spaces.

The string can be determined by four different ways:

  • double quotes
  • single quotes
  • heredoc-syntax
  • nowdoc syntax

Row in double quotes

Line in double quotes:

Control sequences can be used in dual quotes lines. Control sequence - These are special characters designed to format textual output. The following control sequences are available in PHP:

The main property of the lines in double quotes is the ability to process variables inside the rows.


Dollar sign: \\ $ ";

Rows concluded in double quotes may contain single quotes characters:

Echo "Single quotes:" ";

Row in single quotes (apostrophs)

String in single quotes:

$ str \u003d "string"; Echo "One big line can be broken into several small lines so that it is more convenient to read.";

Unlike lines in dual quotes and heredoc syntax, variables and control sequences (for one exception), enclosed in single quotes are not processed. This means that they will be interpreted as conventional string characters:

$ num \u003d 10; Echo "Number: $ num
Dollar sign: \\ $ ";

To the line enclosed in single quotes, one can use single quotes, you need to be shielded using a reverse slash (\\ "). If you need to write the reverse oblique line, you need to duplicate it (\\\\):

Echo "Inside are used \\" Single \\ "quotes"; Echo "Reverse Slash: \\\\";

Rows concluded in single quotes may contain dual quotes characters:

Echo "Double Quotes:" ";

Heredoc-syntax

HereOC-syntax is an alternative way to record rows.

The string determined using the HEREDOC syntax works as well as a string located in double quotes. The difference between Heredoc and a row in double quotes is that using Heredoc there is no need to shield double quotes.

Heredoc-syntax begins with three characters<<< , после которых должен быть указан произвольный идентификатор (назовём его открывающим). Идентификатор может быть указан как в двойных кавычках, так и без них. Immediately After the identifier, the translation should be transferred to a new string, no other characters in addition to the translation to a new string after the identifier should not be, otherwise an error will occur. Next, it goes directly string content. After string content, on a separate line, a closing identifier must be specified (the same as after<<<). Перед ним и после него не должно быть никаких пробелов или других символов, за исключением точки с запятой. Если это правило нарушено, то считается, что закрывающий идентификатор отсутствует и будет вызвана ошибка:

<<

Nowdoc-syntax

Nowdoc-syntax as well as Heredoc is an alternative way to record rows.

The string determined using Nowdoc syntax works as well as a string located in single quotes. The difference between the nowdoc and a string in single quotes is that using the nowdoc there is no need to shield single quotes.

The NOWDOC syntax is similar to HEREDOC with the difference that the opening identifier must necessarily be enclosed in single quotes:

$ num \u003d 10; Echo.<<<"some_id" Число: $num some_id;

Processing variables in lines

There are two types of variable processing syntax in lines: plain and complicated.

Simple syntax - This is when the name of the variable is specified in the string as it is.

When the interpreter meets the dollar sign, it begins to sequentially check whether all the subsequent characters are valid characters in the variable name. Thus, to form the correct variable name, it captures so many characters as possible:

$ STR \u003d "WORLD!"; Echo "Hello $ STR";

Complex syntax - This is when the name of the variable lies in curly brackets.

Since, for processing a variable in a string, the interpreter captures so many characters as possible, as possible when the interpreter is not able to determine independently where the variable name ends:

$ Sport1 \u003d "Will"; $ Sport2 \u003d "Foot"; Echo "I like $ Sport1ball and $ Sport2ball";

In this case, the desired result will not be achieved, since the interpreter will count $ Sport1 as part of the variable name $ Sport1ball, which does not exist.

To explicitly specify an interpreter where the variable name ends, it is necessary to enter the name of the variable in the curly brackets:

$ Sport1 \u003d "Will"; $ Sport2 \u003d "Foot"; Echo "I like ($ Sport1) Bol and ($ SPORT2) Bol.";

The dollar sign can be located both in front of the brace and after it:

$ Sport1 \u003d "Will"; $ Sport2 \u003d "Foot"; Echo "I like $ (Sport1) Bol and ($ SPORT2) Bol.";

Concatenation

Concatenation is a combination of two or more rows in one big one. Combination occurs using a concatenation operator -. (point). When concatenation, each subsequent string is added to the end of the previous one:

The value of any type that is combined with the string will be implicitly converted to the string and then concatenation will be made:

"; Echo" Number: ". 1;?\u003e

I am not an expert in programming on PHP, but I confuse me a little, why I see some code in PHP with a string concluded in single, and sometimes in double quotes.

I just know that V.Net or C language, if it is in single quotes, it means that this is a symbol, not a string.

Decision

What you need to know

$ a \u003d "name"; $ B \u003d "MY $ A"; \u003d\u003d "My Name" $ \u200b\u200bC \u003d "My $ A"; ! \u003d "MY NAME"

In PHP, people use single quotes to determine a constant string, for example "a", "My name", "ABC XYZ" when using double quotes to determine a string containing an identifier, such as "A $ B $ C $ D",

And another thing,

Echo "My Name";

faster than

Echo "My Name";

Echo "My". $ a;

slower than

Echo "MY $ A";

This is true for other rows used.

In PHP, the text in single quotes is considered as a string value, and the text in dual quotes will analyze the variables by replacing and processing their value.

$ test \u003d "variable"; Echo "Hello Mr $ Test"; // The Output Would be: Hello Mr Variable Echo "Hello Mr $ Test"; // The Output Would be: Hello Mr $ Test

Here, double quotation is analyzing the value, and single quotation is considered as a string value (without parsing a $ test variable.)

Both types of nested characters are rows. One type of quotes is convenient to use for the conclusion of another type of quotation. "" "And also" "", the greatest difference between the types of quotes is that references to nested identifiers are replaced inside the double quotes, and not inside single quotes.