What is the difference between single and double quoted strings in PHP? Difference between double and single quotes in PHP Php output quotes.

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

I just know that in .NET or C, if it's in single quotes, it means it's a character, not a string.

Decision

What you should 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 define a constant string like "a", "my name", "abc xyz" while using double quotation marks to define a string containing an identifier like "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 the other strings used.

In PHP, single quoted text is treated as a string value, and double quoted text will parse 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, the double quote parses the value and the single quote is treated as a string value (without parsing the $ test variable.)

Both kinds of nested characters are strings. It is convenient to use one type of quotation for the conclusion of another type of quotation. "" "and" "". The biggest difference between the types of quotation marks is that references to nested identifiers are replaced within double quotation marks, not inside single quotation marks.

The simplest way to define a string is to enclose it in single quotes (the " ).

To use a single quote inside a string, escape it with a backslash ( \ ). If you need to write the backslash itself, duplicate it ( \\ ). All other uses of the backslash will be interpreted as normal characters, which means if you try to use other escape sequences such as \\ r or \\ n, they will be displayed as is instead of any special behavior.

echo "this is a simple string";

echo "Also you can insert into lines
newline character like this,
this is normal"
;

// Outputs: Arnold once said "I" ll be back "
echo "Arnold once said," I \\ "ll be back";

Echo "Have you removed C: \\\\ *. *?";

// Outputs: Have you removed C: \\ *. *?
echo "Have you removed C: \\ *. *?" ;

// Outputs: This will not be expanded: \\ n newline
echo "This will not be expanded: \\ n newline";

// Outputs: Variables $ expand also $ either not expanding
echo "Variables $ expand also don't $ expand";
?>

Double quotes

If the string is enclosed in double quotes ("), PHP recognizes more escape sequences for special characters:

Escape sequences
Sequence Value
\\ n newline (LF or 0x0A (10) in ASCII)
\\ r carriage return (CR or 0x0D (13) in ASCII)
\\ t horizontal tab (HT or 0x09 (9) in ASCII)
\\ v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\\ e escape character (ESC or 0x1B (27) in ASCII) (since PHP 5.4.4)
\\ f page feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double quote
\{1,3} a sequence of characters matching a regular expression character in octal number system
\\ x (1,2) a sequence of characters matching a regular expression character in hexadecimal notation

As with a string enclosed in single quotes, escaping any character will print the backslash itself. Prior to PHP 5.1.1, backslashes in \\ ($ var) was not printed.

Heredoc

A third way to define strings is using the heredoc syntax: <<< ... After this operator, you must specify an identifier, then a line feed. After that comes the string itself, and then the same identifier that closes the insert.

Line should start with a closing identifier, i.e. it must be in the first column of the row. In addition, the identifier must follow the same naming conventions as all other tags in PHP: contain only alphanumeric characters and underscore, and must not start with a number (underscores are allowed).

Attention

It is very important to note that the line with the closing identifier must not contain any other characters except for the semicolon ( ; ). This means that the identifier must not be indented and that there can be no spaces or tabs before or after the semicolon. It is also important to understand that the first character before the closing identifier must be a newline character as defined by your operating system. For example, on UNIX systems, including Mac OS X, this is \\ n... A new line must also begin immediately after the closing identifier.

If this rule is violated and the closing identifier is not "pure", then the closing identifier is considered to be missing and PHP will continue looking for it further. If in this case the correct closing identifier is still not found, then this will cause a parsing error with a line number at the end of the script.

Heredoc cannot be used to initialize class fields. Since PHP 5.3, this limitation only applies to heredocs containing variables.

Example # 1 Invalid example

class foo (
public $ bar \u003d<<bar
EOT;
}
?>

Heredoc text behaves the same as a double-quoted string, without having them. This means that you do not need to escape quotes in the heredoc, but you can still use the above escape sequences. Variables are processed, but when using complex variables inside the heredoc, you need to be as careful as when working with strings.

Example # 2 Example of defining a heredoc string

$ str \u003d<<Example line,
covering several lines,
using heredoc syntax.
EOD;

Class foo
{
var $ foo;
var $ bar;

Function foo ()
{
$ this -\u003e foo \u003d "Foo";
$ this -\u003e
}
}

$ foo \u003d new foo ();
$ name \u003d "MyName";

echo<<My name is "$ name". I am typing $ foo -\u003e foo .
Now I bring out
($ foo -\u003e bar [1]) .
This should output an uppercase "A": \\ x41
EOT;
?>

My name is "MyName". I am typing Foo. Now, I am displaying Bar2. This should output an uppercase "A": A

It is also possible to use the heredoc syntax to pass data through function arguments:

Starting with version 5.3.0, it became possible to initialize static variables and class properties / constants using the heredoc syntax:

Example # 4 Using heredoc to initialize static variables

// Static variables
function foo ()
{
static $ bar \u003d<<There's nothing here...
LABEL;
}

// Class properties / constants
class foo
{
const BAR \u003d<<An example of using a constant
FOOBAR;

Public $ baz \u003d<<Example of using a field
FOOBAR;
}
?>

Since PHP 5.3.0, you can also surround the Heredoc identifier with double quotes:

Nowdoc

Nowdoc is the same for single quoted strings as heredoc is for double quoted strings. Nowdoc is like heredoc but inside it no substitutions are performed... This construct is ideal for embedding PHP code or other large blocks of text without escaping it. In this it is a bit like SGML construct in that it declares a block of text not to be processed.

Nowdoc is indicated by the same sequence <<< which is used in the heredoc, but the identifier following it is enclosed in single quotes, for example, <<<"EOT" ... All the conditions that apply to heredoc identifiers also apply to nowdoc, especially those related to the closing identifier.

Example # 6 A nowdoc example

$ str \u003d<<<"EOD"
Sample text,
spanning multiple lines
using the syntax nowdoc.
EOD;

/ * More complex example with variables. * /
class foo
{
public $ foo;
public $ bar;

Function foo ()
{
$ this -\u003e foo \u003d "Foo";
$ this -\u003e bar \u003d array ("Bar1", "Bar2", "Bar3");
}
}

$ foo \u003d new foo ();
$ name \u003d "MyName";

echo<<<"EOT"
My name is "$ name". I am typing $ foo-\u003e foo.
Now I am typing ($ foo-\u003e bar).
This shouldn't print an uppercase "A": \\ x41
EOT;
?>

The result of this example:

My name is "$ name". I am typing $ foo-\u003e foo. Now I am typing ($ foo-\u003e bar). This shouldn't print an uppercase "A": \\ x41

Comment:

Unlike heredoc, nowdoc can be used in any context with static data. A typical example of initializing class fields or constants:

Example # 7 Example using static data

class foo (
public $ bar \u003d<<<"EOT"
bar
EOT;
}
?>

Comment:

Nowdoc support was added in PHP 5.3.0.

Variable handling

If the string is specified in double quotes, or using heredoc, the variables inside it are processed.

There are two types of syntax: simple and complex. Simple syntax is easier and more convenient. It makes it possible to process a variable, an array value ( array) or object properties ( object) with a minimum of effort.

Complex syntax can be identified by the curly braces surrounding the expression.

Simple syntax

If the interpreter encounters a dollar sign ( $ ), it captures as many characters as possible to form the correct variable name. If you want to precisely define the end of a name, enclose the variable name in curly braces.

$ juice \u003d "apple";

echo "He drank some $ juice juice." ... PHP_EOL;
// doesn't work, "s" is a valid character for a variable name,
// but our variable is named $ juice.
echo "He drank some juice made of $ juices." ;
?>

The result of this example:

He drank some apple juice. He drank some juice made of.

Array element ( array) or object property ( object). In array indices, the closing square bracket ( ] ) marks the end of the index definition. The same rules apply for object properties as for simple variables.

Example # 8 Simple syntax example

$ juices \u003d array ("apple", "orange", "koolaid1" \u003d\u003e "purple");

echo "He drank some $ juices [0] juice." ... PHP_EOL;
echo "He drank some $ juices [1] juice." ... PHP_EOL;
echo "He drank some $ juices [koolaid1] juice." ... PHP_EOL;

class people (
public $ john \u003d "John Smith";
public $ jane \u003d "Jane Smith";
public $ robert \u003d "Robert Paulsen";

Public $ smith \u003d "Smith";
}

$ people \u003d new people ();

echo "$ people -\u003e john drank some $ juices [0] juice." ... PHP_EOL;
echo "$ people -\u003e john then said hello to $ people -\u003e jane." ... PHP_EOL;
echo "$ people -\u003e john" s wife greeted $ people -\u003e robert. ". PHP_EOL;
echo "$ people -\u003e robert greeted the two $ people -\u003e smiths." ; // Won "t work
?>

The result of this example:

He drank some apple juice. He drank some orange juice. He drank some purple juice. John Smith drank some apple juice. John Smith then said hello to Jane Smith. John Smith "s wife greeted Robert Paulsen. Robert Paulsen greeted the two.

For anything more complex, use complex syntax.

Complex (curly) syntax

It is called difficult not because it is difficult to understand, but because it allows the use of complex expressions.

Any scalar variable, array element, or object property mapped to a string can be represented on a string using this syntax. Just write the expression the same way as outside of the line and then enclose it in { and } ... Insofar as { cannot be escaped, this syntax will only be recognized when $ follows immediately after { ... Use {\$ to print {$ ... A few illustrative examples:

// Show all errors
error_reporting (E_ALL);

$ great \u003d "great";

// Doesn't work, outputs: This is (great)
echo "This is ($ great)";

// Works, outputs: This is great
echo "This is ($ great)";
echo "This is $ (great)";

// Works
echo "This square is wide($ square -\u003e width) 00 centimeters. ";

// Works, quoted keys only work with curly brace syntax
echo "This works: ($ arr [" key "])";

// Works
echo "This works: ($ arr [4] [3])";

// This is incorrect for the same reason as $ foo outside
// strings. In other words, this will still work.
// but since PHP looks for the constant foo first, this will call
// E_NOTICE level error (undefined constant).
echo "It is not right:($ arr [foo] [3]) ";

// Works. When using multidimensional arrays internally
// strings always use curly braces
echo "This works: ($ arr [" foo "] [3])";

// Works.
echo "This works:". $ arr ["foo"] [3];

echo "This works too:($ obj -\u003e values \u200b\u200b[3] -\u003e name) ";

echo "This is the value of the variable by name$ name: ($ ($ name)) ";

echo "This is the value of the variable by name that the getName () function returns:($ (getName ())) ";

echo "This is the value of the variable by name that \\ $ object-\u003e getName () returns:($ ($ object -\u003e getName ())) ";

// Doesn't work, outputs: This is what getName () returns: (getName ())
echo "This is what getName () returns: (getName ())";
?>

Using this syntax, it is also possible to access object properties within strings.

class foo (
var $ bar \u003d "I am bar." ;
}

$ foo \u003d new foo ();
$ bar \u003d "bar";
$ baz \u003d array ("foo", "bar", "baz", "quux");
echo "($ foo -\u003e $ bar) \\ n";
echo "($ foo -\u003e $ baz [1]) \\ n";
?>

The result of this example:

I am bar. I am bar.

Comment:

Functions, method calls, static class variables, and class constants works internally {$} since PHP 5. However, the specified value will be treated as a variable name in the same context as the string in which it is defined. Using single curly braces ( {} ) will not work for accessing the values \u200b\u200bof functions, methods, class constants, or static class variables.

// Show all errors
error_reporting (E_ALL);

class beers (
const softdrink \u003d "rootbeer";
public static $ ale \u003d "ipa";
}

$ rootbeer \u003d "A & W";
$ ipa \u003d "Alexander Keith \\" s ";

// This works, outputs: I would like to A & W
echo "I would like to ($ (beers :: softdrink)) \\ n";

// This also works, outputs: I would like Alexander Keith "s
echo "I would like to ($ (beers :: $ ale)) \\ n";
?>

Accessing and modifying a character in a string

Characters in strings can be used and modified by defining their offset from the beginning of the string, starting at zero, in square brackets after the string, for example, $ str. Think of a string as an array of characters for this purpose. If you need to get or replace more than 1 character, you can use the functions substr () and substr_replace ().

Comment: A character in a string can also be accessed using curly braces, for example, $ str (42).

Attention

Attempting to write to an off-line offset will pad the line with spaces up to that offset. Non-integer types will be converted to integers. Wrong offset type will cause level error E_NOTICE... Writing on a negative offset will cause a level error E_NOTICE, and when read will return an empty string. Only the first character of the assigned string is used. Assigning an empty string assigns a NULL byte.

Attention

Strings in PHP are internally arrays of bytes. As a result, accessing or modifying a string at offset is unsafe in terms of multibyte encoding, and should only be performed with strings in single-byte encodings such as ISO-8859-1.

Example # 9 Some string examples

// Get the first character of the string
$ str \u003d "This is a test." ;
$ first \u003d $ str [0];

// Get the third character of the string
$ third \u003d $ str [2];

// Get the last character of the string
$ str \u003d "This is still a test." ;
$ last \u003d $ str [strlen ($ str) - 1];

// Change the last character of the line
$ str \u003d "Look at the sea";
$ str [strlen ($ str) - 1] \u003d "e";

?>

Since PHP 5.4, the line offset must be specified either as an integer or as a string containing numbers, otherwise a warning will be issued. Previously the offset specified by the view string "foo", without warnings converted to 0 .

Example # 10 Differences between PHP 5.3 and PHP 5.4

$ str \u003d "abc";

Var_dump ($ str ["1"]);
var_dump (isset ($ str ["1"]));

Var_dump ($ str ["1.0"]);
var_dump (isset ($ str ["1.0"]));

Var_dump ($ str ["x"]);
var_dump (isset ($ str ["x"]));

Var_dump ($ str ["1x"]);
var_dump (isset ($ str ["1x"]));
?>

The result of running this example in PHP 5.3:

string (1) "b" bool (true) string (1) "b" bool (true) string (1) "a" bool (true) string (1) "b" bool (true)

The result of running this example in PHP 5.4:

string (1) "b" bool (true) Warning: Illegal string offset "1.0" in /tmp/t.php on line 7 string (1) "b" bool (false) Warning: Illegal string offset "x" in / tmp / t.php on line 9 string (1) "a" bool (false) string (1) "b" bool (false)

Comment:

Attempting to access variables of other types (excluding arrays or objects that implement certain interfaces) using or {} silently return NULL.

Comment:

PHP 5.5 added support for accessing characters in string literals using the syntax or {} .

There are many useful functions for modifying strings.

Basic functions are described in the section on string functions, and for advanced search and replace, see the regular expression or Perl-compatible regular expression functions.

Converting to string

The value can be converted to a string by casting (string), or functions strval ()... In expressions where a string is needed, the conversion occurs automatically. This happens when you use functions echo or printor when the value of a variable is compared to a string. Reading the Types and Type Manipulation sections of the manual will make the following clearer. see also settype ().

Arrays are always converted to string "Array"so that you cannot display the contents of the array ( array) using echo or printto see what it contains. To view an individual item, use something like echo $ arr ["foo"]... See below for tips on how to display / view all content.

Objects in PHP 4 were always converted to string "Object"... If you want to display the field values \u200b\u200bof an object ( object) for debugging purposes, read on. If you want to get the class name of the required object use get_class ()... Since PHP 5, the __toString method is also available.

NULL always converts to an empty string.

As you can see above, directly converting arrays, objects, or resources to string does not provide any useful information about the values \u200b\u200bthemselves, other than their types. A better way to output values \u200b\u200bfor debugging is to use functions print_r () and var_dump ().

Most values \u200b\u200bin PHP can be converted to a string for permanent storage. This method is called serialization and can be done using the function serialize ()... In addition, if your PHP installation has WDDX support, serialization to XML is also possible.

Converting strings to numbers

If the string is recognized as a numeric value, the resulting value and type are determined as shown below.

If the string does not contain any of the characters ".", "E", or "E", and the value of the number is placed within the range of integers (defined PHP_INT_MAX), the string will be recognized as an integer ( integer). In all other cases, it is considered a floating point number ( float).

The value is determined by the beginning of the string. If the string begins with a valid numeric value, that value will be used. Otherwise, the value will be 0 (zero). A valid numeric value is one or more digits (which may contain a decimal point), optionally preceded by a sign, followed by an optional exponent. An exponent is an "e" or "E" followed by one or more digits.

$ foo \u003d 1 + "10.5"; // $ foo is float (11.5)
$ foo \u003d 1 + "-1.3e3"; // $ foo is float (-1299)
$ foo \u003d 1 + "bob-1.3e3"; // $ foo is integer (1)
$ foo \u003d 1 + "bob3"; // $ foo is integer (1)
$ foo \u003d 1 + "10 Small Pigs"; // $ foo is integer (11)
$ foo \u003d 4 + "10.2 Little Piggies"; // $ foo is float (14.2)
$ foo \u003d "10.0 pigs" + 1; // $ foo is float (11)
$ foo \u003d "10.0 pigs" + 1.0; // $ foo is float (11)
?>

For more information on this conversion, see the strtod (3) section of the Unix documentation.

If you want to test any of the examples in this section, copy and paste it and the following line to see what happens:

echo "\\ $ foo \u003d\u003d $ foo; type:". gettype ($ foo). "
\\ n ";
?>

Don't expect to get a character code by converting it to an integer (as is done, for example, in C). To convert characters to their ASCII codes and back, use the functions ord () and chr ().

String type implementation details

String type ( string) in PHP is implemented as an array of bytes and an integer containing the length of the buffer. It does not contain any information on how to convert these bytes to characters, leaving this task to the programmer. There are no restrictions on the content of the string, for example, byte with value 0 ("NUL" -byte) can be located anywhere (however, it should be borne in mind that some functions, as stated in this manual, are not "binary-safe", that is, they can pass strings to libraries that ignore data after NUL -byte).

This nature of the string type explains why PHP does not have a separate byte type - strings play that role. Functions that return non-textual data — for example, an arbitrary stream of data read from a network socket — still return strings.

Given the fact that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded in this case. For example, the line "á" equivalent to "\\ xE1" (ISO-8859-1), "\\ xC3 \\ xA1" (UTF-8, C normalization form), "\\ x61 \\ xCC \\ x81" (UTF-8, normalization form D) or some other possible representation? The answer is that the string will be encoded in the way it is written in the script file. Thus, if the script is written in ISO-8859-1 encoding, then the string will be encoded in ISO-8859-1, etc. However, this rule does not apply when Zend Multibyte is enabled: in this case, the script can be written in any encoding (which is specified clearly or determined automatically), and then converted to a specific internal encoding, which will subsequently be used for string literals. Please note that there are some restrictions on the script encoding (or on the internal encoding if Zend Multibyte is enabled): this encoding should almost always be a superset of ASCII, for example, UTF-8 or ISO-8859-1. Also note that state-dependent encodings, where the same byte values \u200b\u200bcan be used in an initial and non-inital shift state, can cause problems.

Of course, to be useful, string functions must make some assumptions about the encoding of the string. Unfortunately, there are quite a lot of different approaches to this question among PHP functions:

  • Some functions assume that the string is encoded in a single-byte encoding, however, they do not need to interpret bytes as specific characters to work correctly. This category includes, for example, substr (), strpos (), strlen () and strcmp ()... Another way of thinking about these functions is by manipulating memory buffers, i.e. they work directly with bytes and their offsets. offsets.
  • Other functions expect to be passed the encoding as a parameter, possibly assuming some default encoding if the encoding parameter was not specified. This function is
  • Finally, there are functions that imply that the string uses a specific encoding, usually UTF-8. Most of the functions from the intl and PCRE extensions fall here (in the latter case, only when specifying the modifier u). Although this is done on purpose, the function utf8_decode () implies UTF-8 encoding and utf8_encode () - ISO-8859-1.

Ultimately, writing correct programs that work with Unicode means carefully avoiding functions that do not work with Unicode and are likely to corrupt the data, and use the correct functions instead, usually from the intl and mbstring extensions. However, using functions capable of handling Unicode is the very beginning. Regardless of the functionality that the language provides, you need to know the specification of Unicode itself. For example, if a program assumes the existence of only lowercase and uppercase letters in the language, then it makes a big mistake.

What kind of quotation marks should I use for strings - apostrophes or classic double quotation marks?

Let's take a look at the difference between double and single quotes in PHP, and use examples to find out when to use which ones.

Variables and escape sequences for special characters found in single-quoted strings are not processed. Strings surrounded by apostrophes are processed by the PHP interpreter much faster than similar strings surrounded by double quotes.

The reason is simple: the PHP interpreter additionally checks for the presence of variables for strings in double quotes, and if such are found, then instead of the name of the variable, its value is inserted into the string. But a string enclosed in apostrophes is perceived by the interpreter as plain text and PHP does not perform any transformations in these strings. I think it's clear that processing single-quoted strings will be faster anyway.

First, let's describe how to define a string, and then check how much faster processing of strings in single quotes will be.

The easiest way to define a string is to enclose it in single quotes ("). To use single quotes within a single quoted string, they must be preceded by a backslash (\\) character, that is, escaped. If the backslash must come before a single quote or at the end of a line, you need to duplicate it If you try to escape any other character, the backslash will also be printed.

Here's an example of using single quotes:
// Outputs: Simple string
echo "Simple string";
// Outputs: I "m here
echo "I \\" m here ";
// Outputs: This will not insert: \\ n a new line
echo "This will not insert: \\ n a newline";
// Output: Variable $ example will not be substituted either
echo "Variable $ example won't be substituted either"; If a string is enclosed in double quotes ("), PHP recognizes more escape sequences for special characters and substitutes its value instead of the variable name. As with single quotes, in order to use double quotes within a string enclosed in double quotes, they must be preceded by a backslash character (\\).

Here's an example of using double quotes:
// Outputs: Simple string
echo "Simple string";
// Output: Firm "Snowdrop" "
echo "Firm \\" Snowdrop \\ "";
// Output: This will break to a new line
echo "This will newline \\ n";
// Output: The variable will be substituted
$ example \u003d "substituted";
echo "Variable $ example"; It should also be remembered that the sequence "\\ n" (newline), "\\ r" (carriage return) is for plain text, not HTML. So you will not see the changes in the browser (only in the source code of the page).

Let's find out how much faster single quotes are double quotes. For measurements, we will write a short test script, and immediately note that if you test it at your place, the results that depend on the hardware of your PC or server will be different.
// Return the timestamp at the beginning of the cycle
$ start \u003d microtime (true);
// Create a loop for 1 million iterations
for ($ i \u003d 0; $ i< 1000000; $i++) {
$ text \u003d "This is a character string";
}
// Calculate the time spent
$ time \u003d (microtime (true) - $ start); Result: 0.09 seconds.

If we replace single quotes with double quotes:
$ text \u003d "This is a character string"; The result will be 0.10 seconds.

As you can see, when using text strings, the difference in execution time is very small, one might even say does not exist at all. The fun begins when we try to combine a string and a variable.
$ text \u003d "Here is the character string $ i"; or
$ text \u003d $ i. "Here is a character string"; Result approximately: 0.27 seconds.

The difference is quite tangible. Concatenation and double quotes clearly affect performance when variables are added to the string.

When the server processes the code, it checks the entire contents of the double quotes for variables, constants, and more. It takes time. And what is between the single quotes is processed by the server as ready-made text and it doesn't care what is there. The difference between the performance of single and double quotes is very insignificant, but if you are developing a highly loaded project, then a few saved milliseconds is already a victory.

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

A string can be defined in four different ways:

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

Double quoted string

Double quoted string:

Escape sequences can be used in double-quoted strings. Control sequence Are special characters for formatting text output. The following escape sequences are available in PHP:

The main feature of double-quoted strings is the ability to process variables within strings.


Dollar sign: \\ $ ";

Strings enclosed in double quotes can contain single quote characters:

Echo "Single quote:" ";

A string in single quotes (apostrophes)

Single quoted string:

$ str \u003d "String"; echo "One large line can be split into several small lines to make it easier to read.";

Unlike double-quoted strings and heredoc syntax, variables and escape sequences (with one exception) that are enclosed in single quotes are not processed. This means they will be interpreted as normal string characters:

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

To be able to use single quotes in a string enclosed in single quotes, you need to escape them with a backslash (\\ "). If you need to write the backslash itself, you need to duplicate it (\\\\):

Echo "Inside \\" single \\ "quotes" are used; echo "Backslash: \\\\";

Strings enclosed in single quotation marks can contain double quotation marks:

Echo "Double quote:" ";

Heredoc syntax

Heredoc syntax is an alternative way of writing strings.

A string specified using the Heredoc syntax works the same as a string enclosed in double quotes. The difference between a Heredoc and a double quoted string is that using the Heredoc there is no need to escape the double quotes.

Heredoc syntax starts with three characters<<< , после которых должен быть указан произвольный идентификатор (назовём его открывающим). Идентификатор может быть указан как в двойных кавычках, так и без них. Immediately the identifier must be followed by a newline, no other characters other than a newline after the identifier should be, otherwise an error will occur. Next comes the string content itself. After the string content, on a separate line, there must be a closing identifier (the same as after<<<). Перед ним и после него не должно быть никаких пробелов или других символов, за исключением точки с запятой. Если это правило нарушено, то считается, что закрывающий идентификатор отсутствует и будет вызвана ошибка:

<<

Nowdoc syntax

Nowdoc syntax, like Heredoc, is an alternative way of writing strings.

A string defined using the Nowdoc syntax works the same as a string enclosed in single quotes. The difference between Nowdoc and a single quoted string is that using Nowdoc there is no need to escape single quotes.

Nowdoc syntax is similar to Heredoc with the only difference that the opening identifier must be enclosed in single quotes:

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

Handling Variables in Strings

There are two types of syntax for handling variables in strings: plain and complicated.

Simple syntax - this is when the name of the variable is specified on the line as is.

When the interpreter encounters a dollar sign, it begins sequentially checking if all subsequent characters are valid characters in the variable name. Thus, to form the correct variable name, it captures as many characters as possible:

$ str \u003d "World!"; echo "Hello $ str";

Complex syntax Is when the variable name is enclosed in curly braces.

Since, to process a variable in a string, the interpreter captures as many characters as possible, there are situations when the interpreter is not able to independently determine where the variable name ends:

$ sport1 \u003d "by will"; $ sport2 \u003d "foot"; echo "I like $ sport1ball and $ sport2ball";

In this case, the desired result will not be achieved, since the interpreter will consider $ sport1 as part of the name of the variable $ sport1ball, which does not exist.

To explicitly tell the interpreter where the variable name ends, you need to enclose the variable name in curly braces:

$ sport1 \u003d "by will"; $ sport2 \u003d "foot"; echo "I like ($ sport1) more and ($ sport2) more";

The dollar sign can be placed either before or after the curly brace:

$ sport1 \u003d "by will"; $ sport2 \u003d "foot"; echo "I like $ (sport1) big and ($ sport2) big";

Concatenation

Concatenation is the concatenation of two or more strings into one big string. Concatenation is done using the concatenation operator -. (point). When concatenating, each subsequent line is appended to the end of the previous one:

A value of any type that is combined with a string will be implicitly converted to a string and then concatenated:

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

As you saw in the previous tutorial, the echo command in php is a text output tool. Throughout your PHP career, you will use echo more than any other. So let's take a good look at it!

Line output

To output the string, as we did in the previous lessons, echo is used. It can be used to display text in quotes, variable values, etc. Let's take an example.

I love using PHP!"; ?>

Output of the phrase "Hello!" we are already familiar, there is nothing new here. But the following echo command, as you can see, contains an html tag. It is not forbidden to use html tags, because php gives us dynamics, and the statics and page design are still at the mercy of ordinary html.

Watch out for double quotes!

It's great that you can output HTML inside PHP. However, you must be careful when using HTML or any other string containing quotes! Echo uses quotes to indicate the start and end of a string, so you must use one of the following if you want to use quotes inside echo:

  • Don't use quotes inside a string.
  • Escape inner quotes with a slash. To avoid handling internal quotes, just precede them with a backslash, that is, \\ ".
  • Use single quotes (apostrophes) on inside a string.

See our example below for correct and incorrect use of the echo command:

I love using PHP!"; // OK because we escaped the quotes! Echo"

I love using PHP!
"; // OK because we used an apostrophe" echo "
I love using PHP!
"; ?>

If you want to output a string containing quotes, either use an apostrophe (') or escape quotes by putting a slash in front of them (\\ "). The backslash will tell PHP that you want the character after it not to be processed by the interpreter!

Variable output

It is very easy to display variables. In fact, you don't need to do anything special to display variables in pxp. He can do it himself. Here's an example to help you figure it out:

Result:

Hello Bob. My name is: 4a

Simultaneous output of variables and text strings

You can also output variables in double quotes (for example, "text text $ variable"). By placing a variable inside quotation marks (""), you tell PHP that you want it to take its value, convert it to a string, and output it. The example below shows how to do this trick correctly :)

"; echo" Hi, I "m Bob. Who are you? $ my_string
"; echo" Hi, I "m Bob. Who are you? $ my_string Bobetta"; ?\u003e

Result:

Hello Bob. My name is: Bobetta Hi, I "m Bob. Who are you? Hello Bob. My name is: Hi, I" m Bob. Who are you? Hello Bob. My name is: Bobetta

Placing variables inside a string can save you time and make your code easier to read, but it takes some getting used to. Remember to use quotes, single quotes will not output variable values. Single quotes will just print the variable name to a string, i.e. $ my_string, not "Hello Bob. My name is ".

Echo is not a function!

Echo is not a function, but a language construct. When using functions in PHP, they have a very specific form, which we will definitely look at a little later. For now, just know that echo is a special tool that you will definitely love! : D

PHP string concatenation

Perhaps the most common operation with strings is their concatenation, or joining to one string with another. To concatenate strings, we introduced a special operator "." (point).

Example:


At the output, we get the whole line: “My native country is wide!”.