Home Backend Development PHP Tutorial The difference between PHP single quotes and double quotes_PHP Tutorial

The difference between PHP single quotes and double quotes_PHP Tutorial

Jul 21, 2016 pm 03:42 PM
php and use the difference apostrophe Can exist string definition quotation marks of

1. Define a string  

In PHP, the definition of a string can use single quotes or double quotes. However, the same single or double quotation marks must be used to define the string. For example, 'Hello' and 'Hello' are illegal string definitions. ​
When defining a string, only one kind of quotation mark is considered as the delimiter, that is, single quotation mark or double quotation mark. Thus, if a string begins with a double quote, only the double quote is parsed by the parser. This way, you can include any other character, even single quotes, within the double-quoted string. The following quotation mark strings are legal:
Php code

Copy code The code is as follows:

$s = " I am a 'single quote string' inside a double quote string";
$s = 'I am a "double quote string" inside a single quote string';
$s = "I am a 'single quote string' inside a double quote string";
$s = 'I am a "double quote string" inside a single quote string';

Why doesn't "this" work?" will be divided into three sections. If you want to express double quotes in this string, you can use the escape character "" (backslash) to become "Why doesn't "this" work?"

2. Single and double quotation marks in string variables

PHP allows us to directly include string variables in double quotation mark strings. We can find the following two The result of string processing is the same.
Copy code The code is as follows:

$full_name = $first_name . ' ' . $last_name;
$full_name = "$first_name $last_name";   

Single quote strings and double quote strings are processed differently in PHP. The contents of a double-quoted string can be interpreted and replaced, while the contents of a single-quoted string are always considered ordinary characters. For example:
Php code
Copy code The code is as follows:

$foo = 2;
echo "foo is $foo"; // Print result: foo is 2
echo 'foo is $foo'; // Print result: foo is $foo
echo "foo is $foon"; // Print result: foo is 2 (line feed at the same time)
echo 'foo is $foon'; // Print result: foo is $foon
$foo = 2;
echo "foo is $foo"; // Print result: foo is 2
echo 'foo is $foo'; // Print result: foo is $foo
echo "foo is $foon"; // Print result: foo is 2 (with newline)
echo 'foo is $foon'; // Print result: foo is $foon   

As you can see, even the backslash in a single quote string loses its extended meaning (except Insert backslash \ and insert single quote '). Therefore, when you want to perform variable substitution and include escape sequences such as n (newline) in a string, you should use double quotes. Single quote strings can be used anywhere else. The processing speed of using single quote strings in scripts will be faster, because the PHP parser processes single quote strings in a relatively simple way, while the processing of double quotes also needs to be parsed inside the string. It is therefore more complex and therefore slightly slower to process.
Some problems may arise when referencing complex combinations of variables in strings. The following code will work fine:
Php code
Copy code The code is as follows:

echo "value = $foo";
echo "value = $a[$i]";
echo "value = $foo";
echo "value = $a[$i]";

The following code cannot get the results we want:
echo "value = $a[$i][$j ]"; //We want to print an element of the two-dimensional array $a.
To avoid these potential problems in using strings, we usually separate complex variables from strings, like this: echo 'value = ' . $a[$i][$j];/ / Use dots (.) to connect strings
Another way is to enclose complex variables in curly braces, so that the syntax analyzer can correctly identify them:
echo "value = {$a[$i] [$j]}" //Print an element of the two-dimensional array $a
In this way, a new problem arises. When we want to quote the curly brace character itself in a string, we need to remember to use the escape character:
Php code
Copy code The code is as follows :

$var = 3;
echo "value = {$var}"; // Print result "value = 3"
echo "value = {$var}"; // Print result "value = {3}"
$var = 3;
echo "value = {$var}"; // Print result "value = 3"
echo "value = {$ var}"; // Print result "value = {3}"


3. In SQL statements

This is a problem that is often encountered. The SQL statement inserted into the database uses single quotes to define strings. If you want Inserting a string containing single quotes into the database will cause an error in this SQL statement.
For example: $sql="insert into userinfo (username,password) Values('O'Kefee','123456')"
At this time, one of the methods is to add escape characters to the SQL statement Backslash,
is:...Values('O'Kefee',... ​
Of course, you can also use the function addslashes(), the function of this function is to add escape characters,
is: $s = addslashes("O'Kefee") ...Values('".$s."',... ​
Another method is to set the magic-quotes option in php.ini. Turn on this option and pass the form If there are single quotes in the submitted information, escape characters will be automatically added, so there is no need to use other functions.
Additional: Let’s start with the functions of double quotes and single quotes: The fields will be interpreted by the compiler and then output as HTML code, but the ones inside the single quotes do not need to be interpreted and will be output directly. For example:

Copy the code The code is as follows:
$abc='I love u';
echo $abc //The result is: I love u
echo '$abc' //The result is:$ abc
echo "$abc" //The result is: I love u


So when assigning values ​​to SQL statements in the database, they should also be used in double quotes SQL="select a, b,c from ..." But there will be single quotes in the SQL statement to quote the field name
For example: select * from table where user='abc';
The SQL statement here can be written directly as SQL=" select * from table where user='abc'"
But if it is like the following:


Copy the code The code is as follows:
$user='abc';
SQL1="select * from table where user=' ".$user." ' "; Compare
SQL2="select * from table where user=' abc ' "


I added a little more space between the single quotes and double quotes, I hope you can see it more clearly.
That is, replace 'abc' with '".$user."' all within a single quote. Just split the entire SQL string. SQL1 can be decomposed into the following three parts
1: "select * from table where user=' "
2: $user
3: " ' "
Use . to connect the strings. So you can understand.

1. Quotes define strings

In PHP, usually a string is defined in a pair of quotation marks, such as:
'I am a string in single quotes'
"I am a string in double quotes"
 The PHP parser uses pairs of quotation marks to judge a string. Therefore, all strings must use the same single or double
quotes to define the start and end. For example, the following string definition is illegal:
"I am not a valid string since I have unmatching quote marks'
'Me neither!"
When defining a string, only one type of quotation marks is used Treated as a delimiter, i.e. single or double quotes. Thus, if a string begins with a double quote
, then only the double quotes will be parsed by the parser. This way, you can include any other character within the double-quoted string, even the single-quote
symbol. The following quote strings are legal:
$s = "I am a 'single quote string' inside a double quote string";
$s = 'I am a "double quote string" inside a single quote string';
When PHP encounters a quote corresponding to the beginning of the string, it thinks it has reached the end of the string, so:
"Why doesn't "this" work?"
It is actually used The PHP syntax parser is divided into three parts:
"Why doesn't " - a double quote string containing a single quote
this - extra characters that the parser cannot process
" work?" — — Ordinary string
The above example attempts to include double quotes within a double quote string, and the parser considers the string to end when it encounters the second double quote
. To achieve the purpose of including quotation marks, the parser must ignore its original meaning when encountering ordinary quotation marks in the string. We add a backslash before the quotation mark
to tell PHP: this quotation mark is part of the string. The correct representation is this:
"Why doesn't "that" work?"
A common problem in English strings is the use of apostrophe ', because it is a single quote, and in English
(English possessive case) is very common in strings. You have to be careful with these characters:
'You'd better escape your apostrophes'
You can see that backslash has its special meaning in strings, when we need to include the backslash itself in the string When , you need to add an extra backslash before the
symbol. For example:
$file = "c:windowssystem.ini";
echo $file; // The print result is: c:windowssystem.ini
$file = "c:\windows\system.ini" ;
echo $file; // The print result is: c:windowssystem.ini
Another way to define strings, which can eliminate the trouble of special characters and make it easier to quote longer texts. The string definition method
starts with the <<< symbol followed by a custom string, and the last line ends with the custom string and must be in a box.

2. String connection

Strings can be connected using the string concatenation character (.), such as:
$first_name = 'Charlie';
$last_name = 'Brown';
$full_name = $first_name . ' ' . $last_name;
A common use is to create large blocks of HTML string code, assignment signs (=) and connectors (. ) can be abbreviated and combined into the (.=) symbol
, such as:
$html = '';
$html .= '';
for ( $i=0 ; $i<10 ; $i++) {
$square = $i * $i;
$html .= '';
}
$html .= '
numbersquare
' . $i . '' . $square . '
';

3. Use variables in strings

This feature allows you to avoid using connections symbols to glue together large numbers of simple strings. PHP allows us to directly include the word
string variable in a double-quoted string. We can find that the processing results of the following two strings are the same.
$full_name = $first_name . ' ' . $last_name;
$full_name = "$first_name $last_name";
Single quote strings and double quote strings are processed differently in PHP. The content in the double-quoted string can be interpreted and replaced, while the content in the single-quoted
string is always considered to be ordinary characters. For example:
$foo = 2;
echo "foo is $foo"; // Print result: foo is 2
echo 'foo is $foo'; // Print result: foo is $foo
echo "foo is $foon"; // Print result: foo is 2 (with newline)
echo 'foo is $foon'; // Print result: foo is $foon
As you can see Yes, even the backslash within a single quote string loses its extended meaning (except for the insertion of a backslash \ and the insertion of a single
quote '). Therefore, when you want to perform variable substitution and include escape sequences such as n (newline character) in a string, you should use double quotes
.Single quote strings can be used anywhere else. The processing speed of using single quote strings in scripts will be faster, because the PHP syntax analyzer processes
single quote strings in a relatively simple way, while the processing of double quotes is also complicated inside the string. It needs to be parsed, so it is more complicated, so the processing speed is slightly slower.
Some problems may arise when referencing complex combinations of variables in strings. The following code will work normally:
echo "value = $foo";
echo "value = $a[$i ]";
The following code cannot get the results we want:
echo "value = $a[$i][$j]"; //We want to print a certain part of the two-dimensional array $a element.
To avoid these potential problems in using strings, we usually separate complex variables from strings, like this:
echo 'value = ' . $a[$i][$j ];
Another way is to enclose complex variables in curly braces, so that the parser can correctly identify them:
echo "value = {$a[$i][$j]}" // Print an element of the two-dimensional array $a
In this way, a new problem arises. When we want to quote the curly brace character itself in the string, we need to remember to use the escape character:
$var = 3;
echo "value = {$var}"; // Print the result "value = 3"
echo "value = {$var}"; // Print result "value = {3}"


3. Slashes and SQL statements
Generating HTML code or SQL query statements is often encountered when writing PHP programs and is an interesting thing. Why do I say this?
Because it involves generating another type of code, and you must carefully consider and follow the writing syntax and rules
required by this type of code.
Let’s take a look at an example. If you want to query the user whose name is "O'Keefe" in the database, the usual form of the SQL statement
is like this:
select * from users where last_name = 'O 'Keefe'
Please note that the English possessive character (apostrophe) of the SQL statement needs to be escaped with a backslash. PHP provides some functions to handle such
situations. The function AddSlashes($str) is used to automatically insert backslash escape characters for quotation mark characters in strings:
$last_name = "O'Keefe ";
$sql = "select * from users where last_name = '" . addslashes($last_name) . "'";
 In this example, you also need to enclose the last_name string in single quotes ( SQL syntax requirements), since the double
quotation mark string is used here, there is no need to escape the pair of single quotation marks. The following statement is the equivalent of using a single quoted string:
$sql = 'select * from users where last_name = '' . addslashes($last_name) . ''';
Any time you want to add a string in a database When writing a string in a string, you must ensure that the quotes inside use escape symbols correctly. This is a common mistake made by many PHP
beginners.


4. Double quotation marks and HTML

Unlike SQL statements, double quotation marks are often used to represent strings in standard HTML language (many browsers now have Strong fault tolerance
, allowing single quotes or even no quotes to represent strings in HTML), for example:
$html = ''. $link.'';
$html = "$link";
HTML language does not support backslash escaping. This will be experienced when we use the hidden inputs of the form to transmit data. The best way to set the value of hidden inputs is to use the htmlspecialchars() function to encode it. The following statement can
normally transmit data that may contain double quotes:
 

1. Quotation marks define strings. To achieve the purpose of including quotation marks, the parser must ignore its original meaning when encountering ordinary quotation marks in the string. We add a backslash in front of the quotation mark to tell PHP: This quotation mark is part of the string and is the correct representation. The method is this: single quote strings can be used anywhere else. The processing speed of using single quote strings in scripts will be faster, because the PHP parser processes single quote strings in a relatively simple way, while the processing of double quotes is due to the internal nature of the string. It also requires parsing, so it's more complex, so the processing speed is slightly slower.

This...double quotes are escaped, single quotes are not escaped
For example: /r/n is a newline, but if you write a file with single quotes, it will not be a newline, but a newline Characters, if written into a file with double quotes, are newlines.
Agreed.

http://www.bkjia.com/PHPjc/320827.html

truehttp: //www.bkjia.com/PHPjc/320827.htmlTechArticle1. Define a string In PHP, you can use single quotes or double quotes to define a string. But the same type of single or double quotes must be used to define the string, such as: 'Hello" and...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

The difference between Ether and Bitcoin What is the difference between Ether and Bitcoin The difference between Ether and Bitcoin What is the difference between Ether and Bitcoin Mar 19, 2025 pm 04:54 PM

The difference between Ethereum and Bitcoin is significant. Technically, Bitcoin uses PoW, and Ether has shifted from PoW to PoS. Trading speed is slow for Bitcoin and Ethereum is fast. In application scenarios, Bitcoin focuses on payment storage, while Ether supports smart contracts and DApps. In terms of issuance, the total amount of Bitcoin is 21 million, and there is no fixed total amount of Ether coins. Each security challenge is available. In terms of market value, Bitcoin ranks first, and the price fluctuations of both are large, but due to different characteristics, the price trend of Ethereum is unique.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Detailed introduction to Ouyi okex opening and closing time Detailed introduction to Ouyi okex opening and closing time Mar 18, 2025 pm 01:06 PM

The Ouyi OKEx digital asset trading platform is different from the traditional securities market. It is open for trading 24 hours a day, and users can conduct fiat currency trading, currency trading and contract trading at any time. However, the platform will announce in advance and temporarily adjust trading time or rules in case of system maintenance upgrades or special market events (such as extreme market conditions causing severe market fluctuations), such as suspending trading or modifying contract trading position opening rules. Therefore, it is recommended that users pay close attention to platform announcements and market trends, seize trading opportunities and do a good job in risk management. Only by understanding Ouyi OKEx trading time and rule adjustments can you be at ease in the digital currency market.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Which is better PHP or Laravel? Which is better PHP or Laravel? Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

See all articles