A string is series of characters, where a character is
the same as a byte. This means that PHP only supports a 256-character set,
and hence does not offer native Unicode support. See
details of the string
type.
Note:
On 32-bit builds, a string can be as large as up to 2GB
(2147483647 bytes maximum)
Syntax
A string literal can be specified in four different ways:
-
single quoted
-
double quoted
-
heredoc syntax
-
nowdoc syntax
Single quoted
The simplest way to specify a string is to enclose it in single
quotes (the character '
).
To specify a literal single quote, escape it with a backslash
(). To specify a literal backslash, double it
(\
). All other instances of backslash will be treated
as a literal backslash: this means that the other escape sequences you
might be used to, such as r
or n
,
will be output literally as specified rather than having any special
meaning.
Note:
Unlike the double-quoted
and heredoc syntaxes,
variables and escape sequences
for special characters will not be expanded when they
occur in single quoted strings.
<?php
echo 'this is a simple string';
echo
'You can also have embedded newlines in
strings this way as it is
okay to do';// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I'll be back"';// Outputs: You deleted C:*.*?
echo 'You deleted C:\*.*?';// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';// Outputs: This will not expand: n a newline
echo 'This will not expand: n a newline';// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
Double quoted
If the string is enclosed in double-quotes («), PHP will
interpret the following escape sequences for special characters:
Sequence | Meaning |
---|---|
n |
linefeed (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) |
e |
escape (ESC or 0x1B (27) in ASCII) |
f |
form feed (FF or 0x0C (12) in ASCII) |
\ |
backslash |
$ |
dollar sign |
" |
double-quote |
[0-7]{1,3} |
the sequence of characters matching the regular expression is a character in octal notation, which silently overflows to fit in a byte (e.g. «400» === «00») |
x[0-9A-Fa-f]{1,2} |
the sequence of characters matching the regular expression is a character in hexadecimal notation |
u{[0-9A-Fa-f]+} |
the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the string as that codepoint’s UTF-8 representation |
As in single quoted strings, escaping any other character will
result in the backslash being printed too.
The most important feature of double-quoted strings is the fact
that variable names will be expanded. See
string parsing for
details.
Heredoc
A third way to delimit strings is the heredoc syntax:
<<<
. After this operator, an identifier is
provided, then a newline. The string itself follows, and then
the same identifier again to close the quotation.
The closing identifier may be indented by space or tab, in which case
the indentation will be stripped from all lines in the doc string.
Prior to PHP 7.3.0, the closing identifier must
begin in the first column of the line.
Also, the closing identifier must follow the same naming rules as any
other label in PHP: it must contain only alphanumeric characters and
underscores, and must start with a non-digit character or underscore.
Example #1 Basic Heredoc example as of PHP 7.3.0
<?php
// no indentation
echo <<<END
a
b
c
n
END;// 4 spaces of indentation
echo <<<END
a
b
c
END;
Output of the above example in PHP 7.3:
If the closing identifier is indented further than any lines of the body, then a ParseError will be thrown:
Example #2 Closing identifier must not be indented further than any lines of the body
<?php
echo <<<END
a
b
c
END;
Output of the above example in PHP 7.3:
PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
If the closing identifier is indented, tabs can be used as well, however,
tabs and spaces must not be intermixed regarding
the indentation of the closing identifier and the indentation of the body
(up to the closing identifier). In any of these cases, a ParseError will be thrown.
These whitespace constraints have been included because mixing tabs and
spaces for indentation is harmful to legibility.
Example #3 Different indentation for body (spaces) closing identifier
<?php
// All the following code do not work.
// different indentation for body (spaces) ending marker (tabs)
{
echo <<<END
a
END;
}// mixing spaces and tabs in body
{
echo <<<END
a
END;
}// mixing spaces and tabs in ending marker
{
echo <<<END
a
END;
}
Output of the above example in PHP 7.3:
PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
The closing identifier for the body string is not required to be
followed by a semicolon or newline. For example, the following code
is allowed as of PHP 7.3.0:
Example #4 Continuing an expression after a closing identifier
<?php
$values = [<<<END
a
b
c
END, 'd e f'];
var_dump($values);
Output of the above example in PHP 7.3:
array(2) { [0] => string(11) "a b c" [1] => string(5) "d e f" }
Warning
If the closing identifier was found at the start of a line, then
regardless of whether it was a part of another word, it may be considered
as the closing identifier and causes a ParseError.
Example #5 Closing identifier in body of the string tends to cause ParseError
<?php
$values = [<<<END
a
b
END ING
END, 'd e f'];
Output of the above example in PHP 7.3:
PHP Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6
To avoid this problem, it is safe for you to follow the simple rule:
do not choose the closing identifier that appears in the body
of the text.
Warning
Prior to PHP 7.3.0, it is very important to note that the line with the
closing identifier must contain no other characters, except a semicolon
(;
).
That means especially that the identifier
may not be indented, and there may not be any spaces
or tabs before or after the semicolon. It’s also important to realize that
the first character before the closing identifier must be a newline as
defined by the local operating system. This is n
on
UNIX systems, including macOS. The closing delimiter must also be
followed by a newline.
If this rule is broken and the closing identifier is not «clean», it will
not be considered a closing identifier, and PHP will continue looking for
one. If a proper closing identifier is not found before the end of the
current file, a parse error will result at the last line.
Example #6 Invalid example, prior to PHP 7.3.0
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
// Identifier must not be indented
?>
Example #7 Valid example, even if prior to PHP 7.3.0
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Heredocs containing variables can not be used for initializing class properties.
Heredoc text behaves just like a double-quoted string, without
the double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used. Variables are
expanded, but the same care must be taken when expressing complex variables
inside a heredoc as with strings.
Example #8 Heredoc string quoting example
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;/* More complex example, with variables. */
class foo
{
var $foo;
var $bar;
function
__construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}$foo = new foo();
$name = 'MyName';
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': x41
EOT;
?>
The above example will output:
My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A
It is also possible to use the Heredoc syntax to pass data to function
arguments:
Example #9 Heredoc in arguments example
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
It’s possible to initialize static variables and class
properties/constants using the Heredoc syntax:
Example #10 Using Heredoc to initialize static values
<?php
// Static variables
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}// Class properties/constants
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;
public
$baz = <<<FOOBAR
Property example
FOOBAR;
}
?>
The opening Heredoc identifier may optionally be
enclosed in double quotes:
Example #11 Using double quotes in Heredoc
<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>
Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted
strings. A nowdoc is specified similarly to a heredoc, but no
parsing is done inside a nowdoc. The construct is ideal for
embedding PHP code or other large blocks of text without the need for
escaping. It shares some features in common with the SGML
<![CDATA[ ]]>
construct, in that it declares a
block of text which is not for parsing.
A nowdoc is identified with the same <<<
sequence used for heredocs, but the identifier which follows is enclosed in
single quotes, e.g. <<<'EOT'
. All the rules for
heredoc identifiers also apply to nowdoc identifiers, especially those
regarding the appearance of the closing identifier.
Example #12 Nowdoc string quoting example
<?php
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \ and '.
EOD;
The above example will output:
Example of string spanning multiple lines using nowdoc syntax. Backslashes are always treated literally, e.g. \ and '.
Example #13 Nowdoc string quoting example with variables
<?php
class foo
{
public $foo;
public $bar;
function
__construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': x41
EOT;
?>
The above example will output:
My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': x41
Example #14 Static data example
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Variable parsing
When a string is specified in double quotes or with heredoc,
variables are parsed within it.
There are two types of syntax: a
simple one and a
complex one.
The simple syntax is the most common and convenient. It provides a way to
embed a variable, an array value, or an object
property in a string with a minimum of effort.
The complex syntax can be recognised by the
curly braces surrounding the expression.
Simple syntax
If a dollar sign ($
) is encountered, the parser will
greedily take as many tokens as possible to form a valid variable name.
Enclose the variable name in curly braces to explicitly specify the end of
the name.
<?php
$juice = "apple";
echo
"He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>
The above example will output:
He drank some apple juice. He drank some juice made of . He drank some juice made of apples.
Similarly, an array index or an object property
can be parsed. With array indices, the closing square bracket
(]
) marks the end of the index. The same rules apply to
object properties as to simple variables.
Example #15 Simple syntax example
<?php
$juices = array("apple", "orange", "koolaid1" => "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 = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public
$smith = "Smith";
}$people = new people();
echo
"$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>
The above example will output:
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 .
As of PHP 7.1.0 also negative numeric indices are
supported.
Example #16 Negative numeric indices
<?php
$string = 'string';
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>
The above example will output:
The character at index -2 is n. Changing the character at index -3 to o gives strong.
For anything more complex, you should use the complex 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.
The expression is written the same way as it would appear outside the
string, and then wrapped in {
and
}
. Since {
can not be escaped, this
syntax will only be recognised when the $
immediately
follows the {
. Use {$
to get a
literal {$
. Some examples to make it clear:
<?php
// Show all errors
error_reporting(E_ALL);$great = 'fantastic';// Won't work, outputs: This is { fantastic}
echo "This is { $great}";// Works, outputs: This is fantastic
echo "This is {$great}";// Works
echo "This square is {$square->width}00 centimeters broad.";// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";// Works
echo "This works: {$arr[4][3]}";// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";// Works.
echo "This works: " . $arr['foo'][3];
echo
"This works too: {$obj->values[3]->name}";
echo
"This is the value of the var named $name: {${$name}}";
echo
"This is the value of the var named by the return value of getName(): {${getName()}}";
echo
"This is the value of the var named by the return value of $object->getName(): {${$object->getName()}}";// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";// Won't work, outputs: C:folder{fantastic}.txt
echo "C:folder{$great}.txt"
// Works, outputs: C:folderfantastic.txt
echo "C:\folder\{$great}.txt"
?>
It is also possible to access class properties using variables
within strings using this syntax.
<?php
class foo {
var $bar = 'I am bar.';
}$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}n";
echo "{$foo->{$baz[1]}}n";
?>
The above example will output:
Note:
The value accessed from functions, method calls, static class variables,
and class constants inside
{$}
will be interpreted as the name
of a variable in the scope in which the string is defined. Using
single curly braces ({}
) will not work for
accessing the return values of functions or methods or the
values of class constants or static class variables.
<?php
// Show all errors.
error_reporting(E_ALL);
class
beers {
const softdrink = 'rootbeer';
public static $ale = 'ipa';
}$rootbeer = 'A & W';
$ipa = 'Alexander Keith's';// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}n";// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}n";
?>
String access and modification by character
Characters within strings may be accessed and modified by
specifying the zero-based offset of the desired character after the
string using square array brackets, as in
$str[42]. Think of a string as an
array of characters for this purpose. The functions
substr() and substr_replace()
can be used when you want to extract or replace more than 1 character.
Note:
As of PHP 7.1.0, negative string offsets are also supported. These specify
the offset from the end of the string.
Formerly, negative offsets emittedE_NOTICE
for reading
(yielding an empty string) andE_WARNING
for writing
(leaving the string untouched).
Note:
Prior to PHP 8.0.0, strings could also be accessed using braces, as in
$str{42}, for the same purpose.
This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
Warning
Writing to an out of range offset pads the string with spaces.
Non-integer types are converted to integer.
Illegal offset type emits E_WARNING
.
Only the first character of an assigned string is used.
As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly,
it assigned a NULL byte.
Warning
Internally, PHP strings are byte arrays. As a result, accessing or
modifying a string using array brackets is not multi-byte safe, and
should only be done with strings that are in a single-byte encoding such
as ISO-8859-1.
Note:
As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal
error. Formerly, the empty string was silently converted to an array.
Example #17 Some string examples
<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];// Get the third character of a string
$third = $str[2];// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';?>
String offsets have to either be integers or integer-like strings,
otherwise a warning will be thrown.
Example #18 Example of Illegal String Offsets
<?php
$str = '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 above example will output:
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)
Note:
Accessing variables of other types (not including arrays or objects
implementing the appropriate interfaces) using[]
or
{}
silently returnsnull
.
Note:
Characters within string literals can be accessed
using[]
or{}
.
Note:
Accessing characters within string literals using the
{}
syntax has been deprecated in PHP 7.4.
This has been removed in PHP 8.0.
Converting to string
A value can be converted to a string using the
(string)
cast or the strval() function.
String conversion is automatically done in the scope of an
expression where a string is needed. This happens when using the
echo or print functions, or when a
variable is compared to a string. The sections on
Types and
Type Juggling will make
the following clearer. See also the settype() function.
A bool true
value is converted to the string
"1"
. bool false
is converted to
""
(the empty string). This allows conversion back and
forth between bool and string values.
An int or float is converted to a
string representing the number textually (including the
exponent part for floats). Floating point numbers can be
converted using exponential notation (4.1E+6
).
Note:
As of PHP 8.0.0, the decimal point character is always
a period («.
«). Prior to PHP 8.0.0,
the decimal point character is defined in the script’s locale (category
LC_NUMERIC). See the setlocale() function.
Arrays are always converted to the string
"Array"
; because of this, echo and
print can not by themselves show the contents of an
array. To view a single element, use a construction such as
echo $arr['foo']
. See below for tips on viewing the entire
contents.
In order to convert objects to string, the magic
method __toString must be used.
Resources are always converted to strings with the
structure "Resource id #1"
, where 1
is the resource number assigned to the resource by PHP at
runtime. While the exact structure of this string should not be relied on
and is subject to change, it will always be unique for a given resource
within the lifetime of a script being executed (ie a Web request or CLI
process) and won’t be reused. To get a resource‘s type, use
the get_resource_type() function.
null
is always converted to an empty string.
As stated above, directly converting an array,
object, or resource to a string does
not provide any useful information about the value beyond its type. See the
functions print_r() and var_dump() for
more effective means of inspecting the contents of these types.
Most PHP values can also be converted to strings for permanent
storage. This method is called serialization, and is performed by the
serialize() function.
Details of the String Type
The string in PHP is implemented as an array of bytes and an
integer indicating the length of the buffer. It has no information about how
those bytes translate to characters, leaving that task to the programmer.
There are no limitations on the values the string can be composed of; in
particular, bytes with value 0
(“NUL bytes”) are allowed
anywhere in the string (however, a few functions, said in this manual not to
be “binary safe”, may hand off the strings to libraries that ignore data
after a NUL byte.)
This nature of the string type explains why there is no separate “byte” type
in PHP – strings take this role. Functions that return no textual data – for
instance, arbitrary data read from a network socket – will still return
strings.
Given that PHP does not dictate a specific encoding for strings, one might
wonder how string literals are encoded. For instance, is the string
"á"
equivalent to "xE1"
(ISO-8859-1),
"xC3xA1"
(UTF-8, C form),
"x61xCCx81"
(UTF-8, D form) or any other possible
representation? The answer is that string will be encoded in whatever fashion
it is encoded in the script file. Thus, if the script is written in
ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However,
this does not apply if Zend Multibyte is enabled; in that case, the script
may be written in an arbitrary encoding (which is explicitly declared or is
detected) and then converted to a certain internal encoding, which is then
the encoding that will be used for the string literals.
Note that there are some constraints on the encoding of the script (or on the
internal encoding, should Zend Multibyte be enabled) – this almost always
means that this encoding should be a compatible superset of ASCII, such as
UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where
the same byte values can be used in initial and non-initial shift states
may be problematic.
Of course, in order to be useful, functions that operate on text may have to
make some assumptions about how the string is encoded. Unfortunately, there
is much variation on this matter throughout PHP’s functions:
-
Some functions assume that the string is encoded in some (any) single-byte
encoding, but they do not need to interpret those bytes as specific
characters. This is case of, for instance, substr(),
strpos(), strlen() or
strcmp(). Another way to think of these functions is
that operate on memory buffers, i.e., they work with bytes and byte
offsets.
-
Other functions are passed the encoding of the string, possibly they also
assume a default if no such information is given. This is the case of
htmlentities() and the majority of the
functions in the mbstring extension.
-
Others use the current locale (see setlocale()), but
operate byte-by-byte.
-
Finally, they may just assume the string is using a specific encoding,
usually UTF-8. This is the case of most functions in the
intl extension and in the
PCRE extension
(in the last case, only when theu
modifier is used).
Ultimately, this means writing correct programs using Unicode depends on
carefully avoiding functions that will not work and that most likely will
corrupt the data and using instead the functions that do behave correctly,
generally from the intl and
mbstring extensions.
However, using functions that can handle Unicode encodings is just the
beginning. No matter the functions the language provides, it is essential to
know the Unicode specification. For instance, a program that assumes there is
only uppercase and lowercase is making a wrong assumption.
John ¶
6 years ago
I've been a PHP programmer for a decade, and I've always been using the "single-quoted literal" and "period-concatenation" method of string creation. But I wanted to answer the performance question once and for all, using sufficient numbers of iterations and a modern PHP version. For my test, I used:
php -v
PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
------ Results: -------
* 100 million iterations:
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
63608ms (34.7% slower)
$outstr = "literal$n$data$int$data$float$n";
47218ms (fastest)
$outstr =<<<EOS
literal$n$data$int$data$float$n
EOS;
47992ms (1.64% slower)
$outstr = sprintf('literal%s%s%d%s%f%s', $n, $data, $int, $data, $float, $n);
76629ms (62.3% slower)
$outstr = sprintf('literal%s%5$s%2$d%3$s%4$f%s', $n, $int, $data, $float, $data, $n);
96260ms (103.9% slower)
* 10 million iterations (test adapted to see which of the two fastest methods were faster at adding a newline; either the PHP_EOL literal, or the n string expansion):
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
6228ms (reference for single-quoted without newline)
$outstr = "literal$n$data$int$data$float$n";
4653ms (reference for double-quoted without newline)
$outstr = 'literal' . $n . $data . $int . $data . $float . $n . PHP_EOL;
6630ms (35.3% slower than double-quoted with n newline)
$outstr = "literal$n$data$int$data$float$nn";
4899ms (fastest at newlines)
* 100 million iterations (a test intended to see which one of the two ${var} and {$var} double-quote styles is faster):
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
67048ms (38.2% slower)
$outstr = "literal$n$data$int$data$float$n";
49058ms (1.15% slower)
$outstr = "literal{$n}{$data}{$int}{$data}{$float}{$n}"
49221ms (1.49% slower)
$outstr = "literal${n}${data}${int}${data}${float}${n}"
48500ms (fastest; the differences are small but this held true across multiple runs of the test, and this was always the fastest variable encapsulation style)
* 1 BILLION iterations (testing a completely literal string with nothing to parse in it):
$outstr = 'literal string testing';
23852ms (fastest)
$outstr = "literal string testing";
24222ms (1.55% slower)
It blows my mind. The double-quoted strings "which look so $slow since they have to parse everything for n backslashes and $dollar signs to do variable expansion", turned out to be the FASTEST string concatenation method in PHP - PERIOD!
Single-quotes are only faster if your string is completely literal (with nothing to parse in it and nothing to concatenate), but the margin is very tiny and doesn't matter.
So the "highest code performance" style rules are:
1. Always use double-quoted strings for concatenation.
2. Put your variables in "This is a {$variable} notation", because it's the fastest method which still allows complex expansions like "This {$var['foo']} is {$obj->awesome()}!". You cannot do that with the "${var}" style.
3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.
4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer!
gtisza at gmail dot com ¶
11 years ago
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.
This works:
<?php
$foo = <<<END
abcd
END;
?>
This does not:
<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>
Without semicolon, it works fine:
<?php
foo(<<<END
abcd
END
);
?>
garbage at iglou dot eu ¶
6 years ago
You can use string like array of char (like C)
$a = "String array test";
var_dump($a);
// Return string(17) "String array test"
var_dump($a[0]);
// Return string(1) "S"
// -- With array cast --
var_dump((array) $a);
// Return array(1) { [0]=> string(17) "String array test"}
var_dump((array) $a[0]);
// Return string(17) "S"
- Norihiori
vseokdog at gmail dot com ¶
3 years ago
Don't forget about new E_WARNING and E_NOTICE errors from PHP 7.1.x: they have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.
Example:
$foo = 1 + "bob-1.3e3";
$foo = "10.2 pigs " + 1.0;
Will produce: Warning: A non-numeric value encountered
Read more: https://www.php.net/manual/en/migration71.other-changes.php
sideshowAnthony at googlemail dot com ¶
6 years ago
Something I experienced which no doubt will help someone . . .
In my editor, this will syntax highlight HTML and the $comment:
$html = <<<"EOD"
<b>$comment</b>
EOD;
Using this shows all the same colour:
$html = <<<EOD
<b>$comment</b>
EOD;
making it a lot easier to work with
og at gams dot at ¶
15 years ago
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');
$const = get_defined_constants();
echo <<<END
{$const['TEST']}
END;
Result:
TEST STRING
lelon at lelon dot net ¶
18 years ago
You can use the complex syntax to put the value of both object properties AND object methods inside a string. For example...
<?php
class Test {
public $one = 1;
public function two() {
return 2;
}
}
$test = new Test();
echo "foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".
However, you cannot do this for all values in your namespace. Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
const ONE = 1;
}
echo "foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar". Constants and static properties require you to break up the string.
Ray.Paseur sometimes uses Gmail ¶
4 years ago
md5('240610708') == md5('QNKCDZO')
This comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation. By definition, zero raised to any power is zero.
steve at mrclay dot org ¶
14 years ago
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.
<?php
function doubleQuote($str) {
$ret = '"';
for ($i = 0, $l = strlen($str); $i < $l; ++$i) {
$o = ord($str[$i]);
if ($o < 31 || $o > 126) {
switch ($o) {
case 9: $ret .= 't'; break;
case 10: $ret .= 'n'; break;
case 11: $ret .= 'v'; break;
case 12: $ret .= 'f'; break;
case 13: $ret .= 'r'; break;
default: $ret .= 'x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
}
} else {
switch ($o) {
case 36: $ret .= '$'; break;
case 34: $ret .= '"'; break;
case 92: $ret .= '\\'; break;
default: $ret .= $str[$i];
}
}
}
return $ret . '"';
}
?>
necrodust44 at gmail dot com ¶
8 years ago
String conversion to numbers.
Unfortunately, the documentation is not correct.
«The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).»
It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.
<?php
echo " vf r 1234" + 1; // 1235
var_export ("vf r 1234" == "1234"); // true
?>
However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says
«A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent. A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2.»
But it seems that PHP does not recognise the exponent or the radix character.
<?php
echo "0xEp4" + 1; // 15
?>
strtod also uses the current locale to choose the radix character, but PHP ignores the locale, and the radix character is always 2E. However, PHP uses the locale while converting numbers to strings.
With strtod, the current locale is also used to choose the space characters, I don't know about PHP.
BahmanMD ¶
1 month ago
In PHP 8.2 using ${var} in strings is deprecated, use {$var} instead:
<?php
$juice = "apple";// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of {$juice}s.";
?>
php at richardneill dot org ¶
9 years ago
Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
$x = "0123" + 0;
$y = 0123 + 0;
echo "x is $x, y is $y"; //prints "x is 123, y is 83"
in other words:
* leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
* leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
atnak at chejz dot com ¶
18 years ago
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:
$string = 'a';
var_dump($string[2]); // string(0) ""
var_dump($string[7]); // string(0) ""
$string[7] === ''; // TRUE
It appears that anything past the end of the string gives an empty string.. However, when E_NOTICE is on, the above examples will throw the message:
Notice: Uninitialized string offset: N in FILE on line LINE
This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.
isset($string[7]); // FALSE
$string[7] === NULL; // FALSE
Even though it seems like a not-NULL value of type string, it is still considered unset.
chAlx at findme dot if dot u dot need ¶
14 years ago
To save Your mind don't read previous comments about dates ;)
When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:
<?php
var_dump('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
Richard Neill ¶
15 years ago
Unlike bash, we can't do
echo "a" #beep!
Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple: echo "x07"
headden at karelia dot ru ¶
13 years ago
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:
<?php// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';// Our playground
define('qwe', 'asd');
define('zxc', 5);$a=3;
$b=4;
function
c($a, $b) { return $a+$b; }// Usage
echo "pre {$_expr(1+2)} postn"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} postn"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} postn"; // outputs 'pre 17 post'
// General syntax is {$_expr(...)}
?>
nospam at nospam dot com ¶
6 years ago
Beware that consistent with "String conversion to numbers":
<?phpif ('123abc' == 123) echo '(intstr == int) incorrectly tests as true.';// Because one side is a number, the string is incorrectly converted from intstr to int, which then matches the test number.
// True for all conditionals such as if and switch statements (probably also while loops)!
// This could be a huge security risk when testing/using/saving user input, while expecting and testing for only an integer.
// It seems the only fix is for 123 to be a string as '123' so no conversion happens.
?>
jonijnm at example dot com ¶
5 years ago
Both should work :(
<?phpclass Testing {
public static $VAR = 'static';
public const VAR = 'const';
public function
sayHelloStatic() {
echo "hello: {$this::$VAR}";
}
public function
sayHelloConst() {
echo "hello: {$this::VAR}"; //Parse error: syntax error, unexpected '}', expecting '['
}
}$obj = new Testing();
$obj->sayHelloStatic();
$obj->sayHelloConst();
shd at earthling dot net ¶
13 years ago
If you want a parsed variable surrounded by curly braces, just double the curly braces:
<?php
$foo = "bar";
echo "{{$foo}}";
?>
will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
bishop ¶
16 years ago
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
// end-of-line comment will be masked... so will regular PHP:
echo ($test == 'foo' ? 'bar' : 'baz');
/* c-style comment will be masked, as will other heredocs (not using the same marker) */
echo <<<EOHTML
This is text you'll never see!
EOHTML;
function defintion($params) {
echo 'foo';
}
class definition extends nothing {
function definition($param) {
echo 'do nothing';
}
}
how about syntax errors?; = gone, I bet.
_EOC;
?>
Useful for debugging when C-style just won't do. Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.
Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
mark at manngo dot net ¶
6 years ago
I though that it would be helpful to add this comment so that the information at least appears on the right page on the PHP site.
Note that if you intend to use a double-quoted string with an associative key, you may run into the T_ENCAPSED_AND_WHITESPACE error. Some regard this as one of the less obvious error messages.
An expression such as:
<?php
$fruit=array(
'a'=>'apple',
'b'=>'banana',
// etc
);
"This is a $fruit['a']"; // T_ENCAPSED_AND_WHITESPACE
?>
will definitely fall to pieces.
You can resolve it as follows:
<?php
print "This is a $fruit[a]"; // unquote the key
print "This is a ${fruit['a']}"; // Complex Syntax
print "This is a {$fruit['a']}"; // Complex Syntax variation
?>
I have a personal preference for the last variation as it is more natural and closer to what the expression would be like outside the string.
It’s not clear (to me, at least) why PHP misinterprets the single quote inside the expression but I imagine that it has something to do with the fact quotes are not part of the value string — once the string is already being parsed the quotes just get in the way … ?
Hayley Watson ¶
5 years ago
Any single expression, however complex, that starts with $ (i.e., a variable) can be {}-embedded in a double-quoted string:
<?phpecho "The expression {$h->q()["x}"]->p(9 == 0 ? 17 : 42)} gets parsed just as well as " . $h->q()["x}"]->p(9 == 0 ? 17 : 42) . " does.";?>
greenbluemoonlight at gmail dot com ¶
2 years ago
<?php
\Example # 10 Simple Syntax - Solution for the last "echo" line.class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public
$smith = "Smith";
}$people = new people();
echo
"$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths";
\Won't work
\Outputs: Robert Paulsen greeted the two
/**Solution:**
echo "$people->robert greeted the two $people->smithx08s";
\Will work
\Outputs: Robert Paulsen greeted the two Smiths
?>
-
Home
- php — Invalid body indentation level (expecting an indentation level of at least 4)
173 votes
1 answers
Get the solution ↓↓↓
I just upgraded to PHP 7.3 and I’m getting this error:
Invalid body indentation level (expecting an indentation level of at least 4)
Here is the code:
$html = <<<HTML
<html>
<body>
HTML test
</body>
</html>
HTML;
2021-10-23
Write your answer
300
votes
Answer
Solution:
This is caused by the new flexible Heredoc syntaxes in PHP 7.3.
In previous versions of PHP, the closing marker was not allowed to have indentation:
$string = <<<EOF
Hello
EOF;
As of PHP 7.3, the closing marker can be indented.
In this example,EOF
is indented by 4 spaces. The body of the string will also have 4 spaces stripped from the beginning of each line.
$string = <<<EOF
Hello
EOF;
If the closing marker is indented further than any lines of the body, it will throw a Parse error:
$string = <<<EOF
Hello
EOF;
The reason for the error message is two-fold:
- The closing marker is indented further than 1 or more lines within the body
But perhaps more likely, for those upgrading to PHP 7.3:
- I’ve chosen a marker
HTML
which is also present within the string. Because of the flexible spacing now allowed, PHP was incorrectly detecting that the string had closed before I intended.
Share solution ↓
Additional Information:
Date the issue was resolved:
2021-10-23
Link To Source
Link To Answer
People are also looking for solutions of the problem: dompdf image not found or type unknown
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
HTML
HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
Строки
Строка (тип string) — это набор символов, где символ — это то же самое, что
и байт. Это значит, что PHP поддерживает ровно 256 различных символов, а также то, что в
PHP нет встроенной поддержки Unicode. Смотрите также
подробности реализации строкового типа.
Замечание:
В 32-битных системах и в более ранних версиях PHP, строки (string) не могут быть
более 2 ГБ (2147483647 байт).
Синтаксис
Строка может быть определена четырьмя различными способами:
-
одинарными кавычками
-
двойными кавычками
-
heredoc-синтаксисом
-
nowdoc-синтаксисом
Одинарные кавычки
Простейший способ определить строку — это заключить её в одинарные кавычки
(символ '
).
Чтобы использовать одинарную кавычку внутри строки, проэкранируйте её обратным слешем
(). Если необходимо написать сам обратный слеш, продублируйте его
(\
). Все остальные случаи применения обратного слеша будут
интерпретированы как обычные символы: это означает, что если вы попытаетесь
использовать другие управляющие последовательности, такие как r
или
n
, они будут выведены как есть вместо какого-либо особого поведения.
Замечание:
В отличие от синтаксиса двойных кавычек
и heredoc,
переменные и
управляющие последовательности для специальных символов, заключённых в одинарные
кавычки, не обрабатываются.
<?php
echo 'это простая строка';
echo
'Также вы можете вставлять в строки
символ новой строки вот так,
это нормально';// Выводит: Однажды Арнольд сказал: "I'll be back"
echo 'Однажды Арнольд сказал: "I'll be back"';// Выводит: Вы удалили C:*.*?
echo 'Вы удалили C:\*.*?';// Выводит: Вы удалили C:*.*?
echo 'Вы удалили C:*.*?';// Выводит: Это не будет развёрнуто: n новая строка
echo 'Это не будет развёрнуто: n новая строка';// Выводит: Переменные $expand также $either не разворачиваются
echo 'Переменные $expand также $either не разворачиваются';
?>
Двойные кавычки
Если строка заключена в двойные кавычки («), PHP распознает
следующие управляющие последовательности специальных символов:
Последовательность | Значение |
---|---|
n |
новая строка (LF или 0x0A (10) в ASCII) |
r |
возврат каретки (CR или 0x0D (13) в ASCII) |
t |
горизонтальная табуляция (HT или 0x09 (9) в ASCII) |
v |
вертикальная табуляция (VT или 0x0B (11) в ASCII) |
e |
escape-знак (ESC или 0x1B (27) в ASCII) |
f |
подача страницы (FF или 0x0C (12) в ASCII) |
\ |
обратная косая черта |
$ |
знак доллара |
" |
двойная кавычка |
[0-7]{1,3} |
последовательность символов, соответствующая регулярному выражению символа в восьмеричной системе счисления, который молча переполняется, чтобы поместиться в байт (т.е. «400» === «00») |
x[0-9A-Fa-f]{1,2} |
последовательность символов, соответствующая регулярному выражению символа в шестнадцатеричной системе счисления |
u{[0-9A-Fa-f]+} |
последовательность символов, соответствующая регулярному выражению символа Unicode, которая отображается в строка в представлении UTF-8 |
Как и в строке, заключённой в одинарные кавычки, экранирование любого другого символа
выведет также и сам символ экранирования.
Но самым важным свойством строк в двойных кавычках является обработка переменных.
Смотрите более подробно обработку строк.
Heredoc
Третий способ определения строк — это использование heredoc-синтаксиса:
<<<
. После этого оператора необходимо указать идентификатор,
затем перевод строки. После этого идёт сама строка, а потом этот же идентификатор,
закрывающий вставку.
Закрывающий идентификатор может иметь отступ с помощью пробела или табуляции,
и в этом случае отступ будет удалён из всех строк в строке документа.
До PHP 7.3.0 закрывающий идентификатор должен был находиться в самом начале
новой строки.
Кроме того, закрывающий идентификатор должен соответствовать тем же правилам именования,
что и любая другая метка в PHP: он должен содержать только буквенно-цифровые символы
и подчёркивания и должен начинаться с нецифрового символа или символа подчёркивания.
Пример #1 Базовый пример использования Heredoc в PHP 7.3.0
<?php
// без отступов
echo <<<END
a
b
c
n
END;// 4 отступа
echo <<<END
a
b
c
END;
Результат выполнения данного примера в PHP 7.3:
Если закрывающий идентификатор смещён дальше, чем любая строка тела,
будет выброшено ParseError:
Пример #2 Закрывающий идентификатор не должен иметь отступ больше, чем любая строка тела
<?php
echo <<<END
a
b
c
END;
Результат выполнения данного примера в PHP 7.3:
PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
Если у закрывающего идентификатора есть отступ,
табуляции также могут использоваться, однако табуляции и пробелы не должны
смешиваться в отношении отступа закрывающего идентификатора и отступа тела (вплоть до закрывающего идентификатора).
В любом из этих случаев будет выброшено ParseError.
Эти ограничения на пробелы были включены, потому что смешивание табуляции
и пробелов для отступов вредно для разбора.
Пример #3 Другой отступ для закрывающего идентификатора тела (пробелов)
<?php
// Весь следующий код не работает.
// Другой отступ для закрывающего идентификатора (табов) тела (пробелов)
{
echo <<<END
a
END;
}// смешивание пробелов и табуляции в теле
{
echo <<<END
a
END;
}// смешивание пробелов и табуляции в закрывающем идентификаторе
{
echo <<<END
a
END;
}
Результат выполнения данного примера в PHP 7.3:
PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
За закрывающим идентификатором основной строки не обязательно ставить точку с запятой или новую строку.
Например, начиная с PHP 7.3.0 разрешён следующий код:
Пример #4 Продолжение выражения после закрывающего идентификатора
<?php
$values = [<<<END
a
b
c
END, 'd e f'];
var_dump($values);
Результат выполнения данного примера в PHP 7.3:
array(2) { [0] => string(11) "a b c" [1] => string(5) "d e f" }
Внимание
Если закрывающий идентификатор был найден в начале строки, то независимо от того,
был ли он частью другого слова, его можно рассматривать как закрывающий идентификатор и выбросить ParseError.
Пример #5 Закрывающий идентификатор в теле текста имеет тенденцию вызывать ParseError
<?php
$values = [<<<END
a
b
END ING
END, 'd e f'];
Результат выполнения данного примера в PHP 7.3:
PHP Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6
Чтобы избежать этой проблемы, вы можете безопасно следовать простому правилу:
не выбирайте закрывающий идентификатор, который появляется в теле текста.
Внимание
До PHP 7.3.0 очень важно отметить, что строка с закрывающим идентификатором не должна содержать
других символов, за исключением точки с запятой (;
). Это означает,
что идентификатор не должен вводиться с отступом и что не
может быть никаких пробелов или знаков табуляции до или после точки с запятой. Важно
также понимать, что первым символом перед закрывающим идентификатором должен быть
символ новой строки, определённый в вашей операционной системе. Например, в UNIX
системах, включая macOS, это n
. После закрывающего
идентификатора также сразу должна начинаться новая строка.
Если это правило нарушено и закрывающий идентификатор не является «чистым»,
считается, что закрывающий идентификатор отсутствует и PHP продолжит его поиск
дальше. Если в этом случае верный закрывающий идентификатор так и не будет найден,
то это вызовет ошибку парсинга с номером строки в конце скрипта.
Пример #6 Пример неправильного синтаксиса, до PHP 7.3.0
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
// отступ перед закрывающим идентификатором недопустим
}
?>
Пример #7 Пример правильного синтаксиса, даже до PHP 7.3.0
<?php
class foo {
public $bar = <<<EOT
bar
EOT;
}
?>
Heredoc, содержащий переменные, не может использоваться для инициализации свойств класса.
Heredoc-текст ведёт себя так же, как и строка в двойных кавычках, при этом их не имея.
Это означает, что вам нет необходимости экранировать кавычки в heredoc, но вы
по-прежнему можете использовать вышеперечисленные управляющие последовательности.
Переменные обрабатываются, но с применением сложных переменных внутри heredoc
нужно быть также внимательным, как и при работе со строками.
Пример #8 Пример определения heredoc-строки
<?php
$str = <<<EOD
Пример строки,
охватывающей несколько строк,
с использованием heredoc-синтаксиса.
EOD;/* Более сложный пример с переменными. */
class foo
{
var $foo;
var $bar;
function
__construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}$foo = new foo();
$name = 'Имярек';
echo <<<EOT
Меня зовут "$name". Я печатаю $foo->foo.
Теперь я вывожу {$foo->bar[1]}.
Это должно вывести заглавную букву 'A': x41
EOT;
?>
Результат выполнения данного примера:
Меня зовут "Имярек". Я печатаю Foo. Теперь, я вывожу Bar2. Это должно вывести заглавную букву 'A': A
Также возможно использовать heredoc-синтаксис для передачи данных
через аргументы функции:
Пример #9 Пример применения heredoc в аргументах
<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>
Можно инициализировать статические переменные
и свойства/константы класса с помощью синтаксиса heredoc:
Пример #10 Использование heredoc для инциализации статических переменных
<?php
// Статические переменные
function foo()
{
static $bar = <<<LABEL
Здесь ничего нет...
LABEL;
}// Константы/свойства класса
class foo
{
const BAR = <<<FOOBAR
Пример использования константы
FOOBAR;
public
$baz = <<<FOOBAR
Пример использования поля
FOOBAR;
}
?>
Можно также окружать идентификатор Heredoc
двойными кавычками:
Пример #11 Использование двойных кавычек в heredoc
<?php
echo <<<"FOOBAR"
Привет, мир!
FOOBAR;
?>
Nowdoc
Nowdoc — это то же самое для строк в одинарных кавычках, что и heredoc для строк в
двойных кавычках. Nowdoc похож на heredoc, но внутри него
не осуществляется никаких подстановок. Эта конструкция
идеальна для внедрения PHP-кода или других больших блоков текста без необходимости
его экранирования. В этом он немного похож на SGML-конструкцию
<![CDATA[ ]]>
тем, что объявляет блок текста,
не предназначенный для обработки.
Nowdoc указывается той же последовательностью <<<
,
что используется в heredoc, но последующий за ней идентификатор заключается
в одинарные кавычки, например, <<<'EOT'
.
Все условия, действующие для идентификаторов heredoc также действительны
и для nowdoc, особенно те, что относятся к закрывающему идентификатору.
Пример #12 Пример использования nowdoc
<?php
echo <<<'EOD'
Пример текста,
занимающего несколько строк,
с помощью синтаксиса nowdoc. Обратные слеши всегда обрабатываются буквально,
например, \ и '.
EOD;
Результат выполнения данного примера:
Пример текста, занимающего несколько строк, с помощью синтаксиса nowdoc. Обратные слеши всегда обрабатываются буквально, например, \ и '.
Пример #13 Nowdoc пример цитирования строки с переменными
<?php
/* Более сложный пример с переменными. */
class foo
{
public $foo;
public $bar;
function
__construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}$foo = new foo();
$name = 'Имярек';
echo <<<'EOT'
Меня зовут "$name". Я печатаю $foo->foo.
Теперь я печатаю {$foo->bar[1]}.
Это не должно вывести заглавную 'A': x41
EOT;
?>
Результат выполнения данного примера:
Меня зовут "$name". Я печатаю $foo->foo. Теперь я печатаю {$foo->bar[1]}. Это не должно вывести заглавную 'A': x41
Пример #14 Пример использования статичных данных
<?php
class foo {
public $bar = <<<'EOT'
bar
EOT;
}
?>
Обработка переменных
Если строка указывается в двойных кавычках, либо при помощи heredoc,
переменные внутри неё обрабатываются.
Существует два типа синтаксиса:
простой и
сложный.
Простой синтаксис более лёгок и удобен. Он даёт возможность
обработки переменной, значения массива (array) или
свойства объекта (object) с минимумом усилий.
Сложный синтаксис может быть определён
по фигурным скобкам, окружающим выражение.
Простой синтаксис
Если интерпретатор встречает знак доллара ($
), он захватывает так
много символов, сколько возможно, чтобы сформировать правильное имя переменной. Если
вы хотите точно определить конец имени, заключайте имя переменной в фигурные скобки.
<?php
$juice = "apple";
echo
"He drank some $juice juice.".PHP_EOL;// Некорректно. 's' - верный символ для имени переменной, но переменная имеет имя $juice.
echo "He drank some juice made of $juices.";// Корректно. Строго указан конец имени переменной с помощью скобок:
echo "He drank some juice made of ${juice}s.";
?>
Результат выполнения данного примера:
He drank some apple juice. He drank some juice made of . He drank some juice made of apples.
Аналогично могут быть обработаны элемент массива (array) или свойство
объекта (object). В индексах массива закрывающая квадратная скобка
(]
) обозначает конец определения индекса. Для свойств объекта
применяются те же правила, что и для простых переменных.
Пример #15 Пример простого синтаксиса
<?php
$juices = array("apple", "orange", "koolaid1" => "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 = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public
$smith = "Smith";
}$people = new people();
echo
"$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Не сработает
?>
Результат выполнения данного примера:
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 .
В PHP 7.1.0 добавлена поддержка отрицательных числовых
индексов.
Пример #16 Отрицательные числовые индексы
<?php
$string = 'string';
echo "Символ с индексом -2 равен $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Изменение символа на позиции -3 на 'o' даёт следующую строку: $string.", PHP_EOL;
?>
Результат выполнения данного примера:
Символ с индексом -2 равен n. Изменение символа на позиции -3 на 'o' даёт следующую строку: strong
Для чего-либо более сложного, используйте сложный синтаксис.
Сложный (фигурный) синтаксис
Он называется сложным не потому, что труден в понимании,
а потому что позволяет использовать сложные выражения.
Любая скалярная переменная, элемент массива или свойство объекта, отображаемое в
строку, может быть представлена в строке этим синтаксисом. Выражение записывается так же,
как и вне строки, а затем заключается в {
и }
.
Поскольку {
не может быть экранирован, этот синтаксис будет
распознаваться только когда $
следует непосредственно за {
.
Используйте {$
, чтобы напечатать {$
.
Несколько поясняющих примеров:
<?php
// Показываем все ошибки
error_reporting(E_ALL);$great = 'здорово';// Не работает, выводит: Это { здорово}
echo "Это { $great}";// Работает, выводит: Это здорово
echo "Это {$great}";// Работает
echo "Этот квадрат шириной {$square->width}00 сантиметров.";// Работает, ключи, заключённые в кавычки, работают только с синтаксисом фигурных скобок
echo "Это работает: {$arr['key']}";// Работает
echo "Это работает: {$arr[4][3]}";// Это неверно по той же причине, что и $foo[bar] вне
// строки. Другими словами, это по-прежнему будет работать,
// но поскольку PHP сначала ищет константу foo, это вызовет
// ошибку уровня E_NOTICE (неопределённая константа).
echo "Это неправильно: {$arr[foo][3]}";// Работает. При использовании многомерных массивов внутри
// строк всегда используйте фигурные скобки
echo "Это работает: {$arr['foo'][3]}";// Работает.
echo "Это работает: " . $arr['foo'][3];
echo
"Это тоже работает: {$obj->values[3]->name}";
echo
"Это значение переменной по имени $name: {${$name}}";
echo
"Это значение переменной по имени, которое возвращает функция getName(): {${getName()}}";
echo
"Это значение переменной по имени, которое возвращает $object->getName(): {${$object->getName()}}";// Не работает, выводит: Это то, что возвращает getName(): {getName()}
echo "Это то, что возвращает getName(): {getName()}";// Не работает, выводит: C:folder{fantastic}.txt
echo "C:folder{$great}.txt"// Работает, выводит: C:folderfantastic.txt
echo "C:\folder\{$great}.txt"
?>
С помощью этого синтаксиса также возможен доступ к свойствам объекта внутри строк.
<?php
class foo {
var $bar = 'I am bar.';
}$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}n";
echo "{$foo->{$baz[1]}}n";
?>
Результат выполнения данного примера:
Замечание:
Значение, к которому осуществляется доступ из функций, вызовов методов, статических переменных класса
и констант класса внутри
{$}
, будет интерпретироваться как имя
переменной в области, в которой определена строка. Использование
одинарных фигурных скобок ({}
) не будет работать
для доступа к значениям функций, методов,
констант классов или статических переменных класса.
<?php
// Показываем все ошибки
error_reporting(E_ALL);
class
beers {
const softdrink = 'rootbeer';
public static $ale = 'ipa';
}$rootbeer = 'A & W';
$ipa = 'Alexander Keith's';// Это работает, выводит: Я бы хотел A & W
echo "Я бы хотел {${beers::softdrink}}n";// Это тоже работает, выводит: Я бы хотел Alexander Keith's
echo "Я бы хотел {${beers::$ale}}n";
?>
Доступ к символу в строке и его изменение
Символы в строках можно использовать и модифицировать,
определив их смещение относительно начала строки, начиная с
нуля, в квадратных скобках после строки, например, $str[42].
Думайте о строке для этой цели, как о массиве символов.
Если нужно получить или заменить более 1 символа, можно использовать
функции substr() и substr_replace().
Замечание:
Начиная с PHP 7.1.0, поддерживаются отрицательные значения смещения.
Они задают смещение с конца строки. Ранее отрицательные смещение вызывали
ошибку уровняE_NOTICE
при чтении (возвращая пустую строку)
либоE_WARNING
при записи (оставляя строку без изменений).
Замечание:
До PHP 8.0.0 для доступа к символу в строке (string) также можно было использовать фигурные скобки, например,
$str{42}, для той же цели.
Синтаксис фигурных скобок устарел в PHP 7.4.0 и больше не поддерживается в PHP 8.0.0.
Внимание
Попытка записи в смещение за границами строки дополнит строку
пробелами до этого смещения. Нецелые типы будет преобразованы в целые.
Неверный тип смещения вызовет ошибку уровня E_WARNING
.
Используется только первый символ присваемой строки.
Начиная с PHP 7.1.0, присвоение пустой строки вызовет фатальную ошибку. Ранее
в таком случае присваивался нулевой байт (NULL).
Внимание
Строки в PHP внутренне представляют из себя массивы байт. Как результат,
доступ или изменение строки по смещению небезопасно с точки зрения многобайтной
кодировки, и должно выполняться только со строками в однобайтных кодировках,
таких как, например, ISO-8859-1.
Замечание:
Начиная с PHP 7.1.0, использование пустого индекса вызывает фатальную ошибку,
ранее в подобном случае строка преобразовывалась в массив без предупреждения.
Пример #17 Несколько примеров строк
<?php
// Получение первого символа строки
$str = 'This is a test.';
$first = $str[0];// Получение третьего символа строки
$third = $str[2];// Получение последнего символа строки
$str = 'This is still a test.';
$last = $str[strlen($str)-1];// Изменение последнего символа строки
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';?>
Смещение в строке должно задаваться либо целым числом, либо строкой,
содержащей цифры, иначе будет выдаваться предупреждение.
Пример #18 Пример недопустимого смещения строки
<?php
$str = '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']));
?>
Результат выполнения данного примера:
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)
Замечание:
Попытка доступа к переменным других типов (исключая массивы или
объекты, реализующие определённые интерфейсы) с помощью[]
или{}
молча вернётnull
.
Замечание:
Доступ к символам в строковых литералах можно получить
с помощью синтаксиса[]
или{}
.
Замечание:
Доступ к символам в строковых литералах с использованием
синтаксиса{}
объявлен устаревшим в PHP 7.4.
Функционал удалён в PHP 8.0.
Преобразование в строку
Значение может быть преобразовано в строку с помощью приведения
(string)
, либо функции strval().
В выражениях, где необходима строка, преобразование происходит автоматически.
Это происходит, когда вы используете функции echo
или print, либо когда значение переменной сравнивается
со строкой. Прочтение разделов руководства Типы и Манипуляции с типами сделает
следующее более понятным. Смотрите также settype().
Значение bool true
преобразуется в строку
"1"
, а значение false
преобразуется в
""
(пустую строку). Это позволяет преобразовывать значения
в обе стороны — из булева типа в строковый и наоборот.
Целое (int) или число с плавающей точкой
(float) преобразуется в строку, представленную числом,
состоящим из его цифр (включая показатель степени для чисел с плавающей
точкой). Числа с плавающей точкой могут быть преобразованы с помощью
экспоненциального представления (4.1E+6
).
Замечание:
Начиная с PHP 8.0.0, символом десятичной точки всегда является
точка («.
«). До PHP 8.0.0 символ десятичной точки определялся в локали скрипта
(категория LC_NUMERIC). Смотрите функцию setlocale()
Массивы всегда преобразуются в строку "Array"
,
так что вы не можете отобразить содержимое массива (array),
используя echo или print,
чтобы узнать, что он содержит. Чтобы просмотреть отдельный элемент, используйте
что-нибудь вроде echo $arr['foo']
. Смотрите
ниже советы о том, как отобразить/просмотреть все содержимое.
Для преобразования переменной типа "Object"
в тип string
используется магический метод
__toString.
Тип ресурс (resource) всегда преобразуется в строку (string) вида
"Resource id #1"
, где 1
является
номером ресурса привязанного к resource во время выполнения.
И хотя не стоит точно полагаться на эту строку, которая может быть изменена в будущем,
она всегда будет уникальной для текущего запуска скрипта (т.е. веб-запроса или
CLI-процесса) и не может использоваться повторно для другого ресурса.
Если вы хотите получить тип ресурса, используйте get_resource_type().
Значение null
всегда преобразуется в пустую строку.
Как вы могли видеть выше, прямое преобразование в строку массивов, объектов
или ресурсов не даёт никакой полезной информации о самих значениях, кроме их типов.
Более подходящий способ вывода значений для отладки — использовать функции
print_r() и var_dump().
Большинство значений в PHP может быть преобразовано в строку для постоянного
хранения. Этот метод называется сериализацией и может быть выполнен
при помощи функции
serialize().
Подробности реализации строкового типа
Строковый тип (string) в PHP реализован в виде массива
байт и целого числа, содержащего длину буфера. Он не содержит никакой
информации о способе преобразования этих байт в символы, предоставляя
эту задачу программисту. Нет никаких ограничений на содержимое строки,
например, байт со значением 0
(«NUL»-байт) может
располагаться где угодно (однако, стоит учитывать, что некоторые функции,
как сказано в этом руководстве, не являются «бинарно-безопасными»,
т.е. они могут передавать строки библиотекам, которые игнорируют
данные после NUL-байта).
Данная природа строкового типа объясняет почему в PHP нет отдельного
типа «byte» — строки играют эту роль. Функции, возвращающие нетекстовые данные
— например, произвольный поток данных, считываемый из сетевого сокета
— тем не менее возвращают строки.
Принимая во внимание тот факт, что PHP не диктует определённую кодировку
для строк, можно задать вопрос, как в таком случае кодируются строковые
литералы. Например, строка "á"
эквивалентна
"xE1"
(ISO-8859-1), "xC3xA1"
(UTF-8, форма нормализации C), "x61xCCx81"
(UTF-8, форма нормализации D) или какому-либо другому возможному
представлению? Ответом является следующее: строка будет закодирована тем
образом, которым она записана в файле скрипта. Таким образом, если
скрипт записан в кодировке ISO-8859-1, то и строка будет закодирована в
ISO-8859-1 и т.д. Однако, это правило не применяется при включённом
режиме Zend Multibyte: в этом случае скрипт может быть записан в любой
кодировке (которая указывается ясно или определяется автоматически),
а затем конвертируются в определённую внутреннюю кодировку, которая и будет
впоследствии использована для строковых литералов.
Учтите, что на кодировку скрипта (или на внутреннюю кодировку, если
включён режим Zend Multibyte) накладываются некоторые ограничения:
практически всегда данная кодировка должна быть надмножеством ASCII,
например, UTF-8 или ISO-8859-1. Учтите также, что кодировки, зависящие
от состояния, где одни и те же значения байт могут быть использованы
в начальном и не начальном состоянии сдвига, могут вызвать проблемы.
Разумеется, чтобы приносить пользу, строковые функции должны сделать
некоторые предположения о кодировке строки. К несчастью, среди
PHP-функций довольно большое разнообразие подходов к этому вопросу:
-
Некоторые функции предполагают, что строка закодирована в какой-либо
однобайтовой кодировке, однако, для корректной работы им
не требуется интерпретировать байты как определённые символы.
Под эту категорию попадают, например, substr(),
strpos(), strlen() и
strcmp(). Другой способ мышления об этих функциях
представляет собой оперирование буферами памяти, т.е. они работают
непосредственно с байтами и их смещениями.
-
Другие функции ожидают передачу кодировку в виде параметра, возможно,
предполагая некоторую кодировку по умолчанию, если параметр с кодировкой
не был указан. Такой функцией является htmlentities()
и большинство функций из модуля
mbstring.
-
Другие функции используют текущие установки локали (смотрите
setlocale()), но оперируют побайтово.
-
Наконец, есть функции, подразумевающие, что строка использует
определённую кодировку, обычно UTF-8. Сюда попадают большинство
функций из модулей intl
и PCRE
(в последнем случае, только при указании модификатора
u
).
В конечном счёте, написание корректных программ, работающих с Unicode,
означает осторожное избегание функций, которые не работают с Unicode
и, скорее всего, испортят данные, и использование вместо них корректных
функций, обычно из модулей intl
и mbstring.
Однако, использование функций, способных работать с Unicode, является
самым началом. Вне зависимости от тех функций, которые предоставляет
язык, необходимо знать спецификацию самого Unicode. Например, если
программа предполагает существование в языке только строчных и
заглавных букв, то она делает большую ошибку.
John ¶
6 years ago
I've been a PHP programmer for a decade, and I've always been using the "single-quoted literal" and "period-concatenation" method of string creation. But I wanted to answer the performance question once and for all, using sufficient numbers of iterations and a modern PHP version. For my test, I used:
php -v
PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
------ Results: -------
* 100 million iterations:
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
63608ms (34.7% slower)
$outstr = "literal$n$data$int$data$float$n";
47218ms (fastest)
$outstr =<<<EOS
literal$n$data$int$data$float$n
EOS;
47992ms (1.64% slower)
$outstr = sprintf('literal%s%s%d%s%f%s', $n, $data, $int, $data, $float, $n);
76629ms (62.3% slower)
$outstr = sprintf('literal%s%5$s%2$d%3$s%4$f%s', $n, $int, $data, $float, $data, $n);
96260ms (103.9% slower)
* 10 million iterations (test adapted to see which of the two fastest methods were faster at adding a newline; either the PHP_EOL literal, or the n string expansion):
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
6228ms (reference for single-quoted without newline)
$outstr = "literal$n$data$int$data$float$n";
4653ms (reference for double-quoted without newline)
$outstr = 'literal' . $n . $data . $int . $data . $float . $n . PHP_EOL;
6630ms (35.3% slower than double-quoted with n newline)
$outstr = "literal$n$data$int$data$float$nn";
4899ms (fastest at newlines)
* 100 million iterations (a test intended to see which one of the two ${var} and {$var} double-quote styles is faster):
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
67048ms (38.2% slower)
$outstr = "literal$n$data$int$data$float$n";
49058ms (1.15% slower)
$outstr = "literal{$n}{$data}{$int}{$data}{$float}{$n}"
49221ms (1.49% slower)
$outstr = "literal${n}${data}${int}${data}${float}${n}"
48500ms (fastest; the differences are small but this held true across multiple runs of the test, and this was always the fastest variable encapsulation style)
* 1 BILLION iterations (testing a completely literal string with nothing to parse in it):
$outstr = 'literal string testing';
23852ms (fastest)
$outstr = "literal string testing";
24222ms (1.55% slower)
It blows my mind. The double-quoted strings "which look so $slow since they have to parse everything for n backslashes and $dollar signs to do variable expansion", turned out to be the FASTEST string concatenation method in PHP - PERIOD!
Single-quotes are only faster if your string is completely literal (with nothing to parse in it and nothing to concatenate), but the margin is very tiny and doesn't matter.
So the "highest code performance" style rules are:
1. Always use double-quoted strings for concatenation.
2. Put your variables in "This is a {$variable} notation", because it's the fastest method which still allows complex expansions like "This {$var['foo']} is {$obj->awesome()}!". You cannot do that with the "${var}" style.
3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.
4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer!
gtisza at gmail dot com ¶
11 years ago
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.
This works:
<?php
$foo = <<<END
abcd
END;
?>
This does not:
<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>
Without semicolon, it works fine:
<?php
foo(<<<END
abcd
END
);
?>
garbage at iglou dot eu ¶
6 years ago
You can use string like array of char (like C)
$a = "String array test";
var_dump($a);
// Return string(17) "String array test"
var_dump($a[0]);
// Return string(1) "S"
// -- With array cast --
var_dump((array) $a);
// Return array(1) { [0]=> string(17) "String array test"}
var_dump((array) $a[0]);
// Return string(17) "S"
- Norihiori
vseokdog at gmail dot com ¶
3 years ago
Don't forget about new E_WARNING and E_NOTICE errors from PHP 7.1.x: they have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.
Example:
$foo = 1 + "bob-1.3e3";
$foo = "10.2 pigs " + 1.0;
Will produce: Warning: A non-numeric value encountered
Read more: https://www.php.net/manual/en/migration71.other-changes.php
sideshowAnthony at googlemail dot com ¶
6 years ago
Something I experienced which no doubt will help someone . . .
In my editor, this will syntax highlight HTML and the $comment:
$html = <<<"EOD"
<b>$comment</b>
EOD;
Using this shows all the same colour:
$html = <<<EOD
<b>$comment</b>
EOD;
making it a lot easier to work with
og at gams dot at ¶
15 years ago
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');
$const = get_defined_constants();
echo <<<END
{$const['TEST']}
END;
Result:
TEST STRING
lelon at lelon dot net ¶
18 years ago
You can use the complex syntax to put the value of both object properties AND object methods inside a string. For example...
<?php
class Test {
public $one = 1;
public function two() {
return 2;
}
}
$test = new Test();
echo "foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".
However, you cannot do this for all values in your namespace. Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
const ONE = 1;
}
echo "foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar". Constants and static properties require you to break up the string.
Ray.Paseur sometimes uses Gmail ¶
4 years ago
md5('240610708') == md5('QNKCDZO')
This comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation. By definition, zero raised to any power is zero.
steve at mrclay dot org ¶
14 years ago
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.
<?php
function doubleQuote($str) {
$ret = '"';
for ($i = 0, $l = strlen($str); $i < $l; ++$i) {
$o = ord($str[$i]);
if ($o < 31 || $o > 126) {
switch ($o) {
case 9: $ret .= 't'; break;
case 10: $ret .= 'n'; break;
case 11: $ret .= 'v'; break;
case 12: $ret .= 'f'; break;
case 13: $ret .= 'r'; break;
default: $ret .= 'x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
}
} else {
switch ($o) {
case 36: $ret .= '$'; break;
case 34: $ret .= '"'; break;
case 92: $ret .= '\\'; break;
default: $ret .= $str[$i];
}
}
}
return $ret . '"';
}
?>
necrodust44 at gmail dot com ¶
8 years ago
String conversion to numbers.
Unfortunately, the documentation is not correct.
«The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).»
It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.
<?php
echo " vf r 1234" + 1; // 1235
var_export ("vf r 1234" == "1234"); // true
?>
However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says
«A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent. A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2.»
But it seems that PHP does not recognise the exponent or the radix character.
<?php
echo "0xEp4" + 1; // 15
?>
strtod also uses the current locale to choose the radix character, but PHP ignores the locale, and the radix character is always 2E. However, PHP uses the locale while converting numbers to strings.
With strtod, the current locale is also used to choose the space characters, I don't know about PHP.
BahmanMD ¶
1 month ago
In PHP 8.2 using ${var} in strings is deprecated, use {$var} instead:
<?php
$juice = "apple";// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of {$juice}s.";
?>
php at richardneill dot org ¶
9 years ago
Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
$x = "0123" + 0;
$y = 0123 + 0;
echo "x is $x, y is $y"; //prints "x is 123, y is 83"
in other words:
* leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
* leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
atnak at chejz dot com ¶
18 years ago
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:
$string = 'a';
var_dump($string[2]); // string(0) ""
var_dump($string[7]); // string(0) ""
$string[7] === ''; // TRUE
It appears that anything past the end of the string gives an empty string.. However, when E_NOTICE is on, the above examples will throw the message:
Notice: Uninitialized string offset: N in FILE on line LINE
This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.
isset($string[7]); // FALSE
$string[7] === NULL; // FALSE
Even though it seems like a not-NULL value of type string, it is still considered unset.
chAlx at findme dot if dot u dot need ¶
14 years ago
To save Your mind don't read previous comments about dates ;)
When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:
<?php
var_dump('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
Richard Neill ¶
15 years ago
Unlike bash, we can't do
echo "a" #beep!
Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple: echo "x07"
headden at karelia dot ru ¶
13 years ago
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:
<?php// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';// Our playground
define('qwe', 'asd');
define('zxc', 5);$a=3;
$b=4;
function
c($a, $b) { return $a+$b; }// Usage
echo "pre {$_expr(1+2)} postn"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} postn"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} postn"; // outputs 'pre 17 post'
// General syntax is {$_expr(...)}
?>
nospam at nospam dot com ¶
6 years ago
Beware that consistent with "String conversion to numbers":
<?phpif ('123abc' == 123) echo '(intstr == int) incorrectly tests as true.';// Because one side is a number, the string is incorrectly converted from intstr to int, which then matches the test number.
// True for all conditionals such as if and switch statements (probably also while loops)!
// This could be a huge security risk when testing/using/saving user input, while expecting and testing for only an integer.
// It seems the only fix is for 123 to be a string as '123' so no conversion happens.
?>
jonijnm at example dot com ¶
5 years ago
Both should work :(
<?phpclass Testing {
public static $VAR = 'static';
public const VAR = 'const';
public function
sayHelloStatic() {
echo "hello: {$this::$VAR}";
}
public function
sayHelloConst() {
echo "hello: {$this::VAR}"; //Parse error: syntax error, unexpected '}', expecting '['
}
}$obj = new Testing();
$obj->sayHelloStatic();
$obj->sayHelloConst();
shd at earthling dot net ¶
13 years ago
If you want a parsed variable surrounded by curly braces, just double the curly braces:
<?php
$foo = "bar";
echo "{{$foo}}";
?>
will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
bishop ¶
16 years ago
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
// end-of-line comment will be masked... so will regular PHP:
echo ($test == 'foo' ? 'bar' : 'baz');
/* c-style comment will be masked, as will other heredocs (not using the same marker) */
echo <<<EOHTML
This is text you'll never see!
EOHTML;
function defintion($params) {
echo 'foo';
}
class definition extends nothing {
function definition($param) {
echo 'do nothing';
}
}
how about syntax errors?; = gone, I bet.
_EOC;
?>
Useful for debugging when C-style just won't do. Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.
Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
mark at manngo dot net ¶
6 years ago
I though that it would be helpful to add this comment so that the information at least appears on the right page on the PHP site.
Note that if you intend to use a double-quoted string with an associative key, you may run into the T_ENCAPSED_AND_WHITESPACE error. Some regard this as one of the less obvious error messages.
An expression such as:
<?php
$fruit=array(
'a'=>'apple',
'b'=>'banana',
// etc
);
"This is a $fruit['a']"; // T_ENCAPSED_AND_WHITESPACE
?>
will definitely fall to pieces.
You can resolve it as follows:
<?php
print "This is a $fruit[a]"; // unquote the key
print "This is a ${fruit['a']}"; // Complex Syntax
print "This is a {$fruit['a']}"; // Complex Syntax variation
?>
I have a personal preference for the last variation as it is more natural and closer to what the expression would be like outside the string.
It’s not clear (to me, at least) why PHP misinterprets the single quote inside the expression but I imagine that it has something to do with the fact quotes are not part of the value string — once the string is already being parsed the quotes just get in the way … ?
Hayley Watson ¶
5 years ago
Any single expression, however complex, that starts with $ (i.e., a variable) can be {}-embedded in a double-quoted string:
<?phpecho "The expression {$h->q()["x}"]->p(9 == 0 ? 17 : 42)} gets parsed just as well as " . $h->q()["x}"]->p(9 == 0 ? 17 : 42) . " does.";?>
greenbluemoonlight at gmail dot com ¶
2 years ago
<?php
\Example # 10 Simple Syntax - Solution for the last "echo" line.class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public
$smith = "Smith";
}$people = new people();
echo
"$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths";
\Won't work
\Outputs: Robert Paulsen greeted the two
/**Solution:**
echo "$people->robert greeted the two $people->smithx08s";
\Will work
\Outputs: Robert Paulsen greeted the two Smiths
?>
The following PHP code fails to be parsed by parseCode()
with an «Invalid body indentation level» error:
<?php $x = <<<'NOWDOC' ... NOWDOC; $y = "_$z";
Detailed error stack
SyntaxError: Invalid body indentation level (expecting an indentation at least 4) on line 7
at parser.raiseError (node_modules/php-parser/src/parser.js:330:17)
at parser.check_heredoc_indentation_level (node_modules/php-parser/src/parser/scalar.js:136:14)
at parser.remove_heredoc_leading_whitespace_chars (node_modules/php-parser/src/parser/scalar.js:63:10)
at parser.read_encapsed_string_item (node_modules/php-parser/src/parser/scalar.js:343:18)
at parser.read_encapsed_string (node_modules/php-parser/src/parser/scalar.js:445:23)
at parser.read_scalar (node_modules/php-parser/src/parser/scalar.js:271:23)
at parser.read_expr_item (node_modules/php-parser/src/parser/expr.js:489:19)
at parser.read_expr (node_modules/php-parser/src/parser/expr.js:18:19)
at parser.read_expr_item (node_modules/php-parser/src/parser/expr.js:419:46)
at parser.read_expr (node_modules/php-parser/src/parser/expr.js:18:19) {
lineNumber: 7,
fileName: 'eval',
columnNumber: 7
}
The interesting thing here is the combination: the error appears when all of the following conditions are met:
-
$x
is assigned with a Nowdoc block (not Heredoc). -
That Nowdoc block is a flexible Nowdoc, i.e. the closing marker must be indented.
-
The string assigned to
$y
needs to have an interpolated variable ($z
in the example). -
The string assigned to
$y
needs to have a character before the interpolation. I picked the underscore in this example, but basically any character will suffice.Notable exceptions that will not trigger the error are the following:
- Spaces
- Newlines
- a single Backspace (as it escapes the interpolation)
- an opening brace as part of an interpolation-enclosing pair:
It appears to me that the flexible Nowdoc is not properly «closed» by the parser and it tries to apply Nowdoc rules to the next string as well: If 4 spaces are added to the start of the string like this:
…the parser will accept that.
A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.
Note: On 32-bit builds, a string can be as large as up to 2GB (2147483647 bytes maximum)
Syntax
A string literal can be specified in four different ways:
- single quoted
- double quoted
- heredoc syntax
- nowdoc syntax
Single quoted
The simplest way to specify a string is to enclose it in single quotes (the character '
).
To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (
\
). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as r
or n
, will be output literally as specified rather than having any special meaning.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; echo 'Arnold once said: "I'll be back"'; echo 'You deleted C:\*.*?'; echo 'You deleted C:*.*?'; echo 'This will not expand: n a newline'; echo 'Variables do not $expand $either'; ?>
Double quoted
If the string is enclosed in double-quotes («), PHP will interpret the following escape sequences for special characters:
Sequence | Meaning |
---|---|
n |
linefeed (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) |
e |
escape (ESC or 0x1B (27) in ASCII) |
f |
form feed (FF or 0x0C (12) in ASCII) |
\ |
backslash |
$ |
dollar sign |
" |
double-quote |
[0-7]{1,3} |
the sequence of characters matching the regular expression is a character in octal notation, which silently overflows to fit in a byte (e.g. «400» === «00») |
x[0-9A-Fa-f]{1,2} |
the sequence of characters matching the regular expression is a character in hexadecimal notation |
u{[0-9A-Fa-f]+} |
the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the string as that codepoint’s UTF-8 representation |
As in single quoted strings, escaping any other character will result in the backslash being printed too.
The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
Heredoc
A third way to delimit strings is the heredoc syntax: <<<
. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.
The closing identifier may be indented by space or tab, in which case the indentation will be stripped from all lines in the doc string. Prior to PHP 7.3.0, the closing identifier must begin in the first column of the line.
Also, the closing identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Example #1 Basic Heredoc example as of PHP 7.3.0
<?php echo <<<END a b c n END; echo <<<END a b c END;
Output of the above example in PHP 7.3:
If the closing identifier is indented further than any lines of the body, then a ParseError will be thrown:
Example #2 Closing identifier must not be indented further than any lines of the body
<?php echo <<<END a b c END;
Output of the above example in PHP 7.3:
PHP Parse error: Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
If the closing identifier is indented, tabs can be used as well, however, tabs and spaces must not be intermixed regarding the indentation of the closing identifier and the indentation of the body (up to the closing identifier). In any of these cases, a ParseError will be thrown. These whitespace constraints have been included because mixing tabs and spaces for indentation is harmful to legibility.
Example #3 Different indentation for body (spaces) closing identifier
<?php { echo <<<END a END; } { echo <<<END a END; } { echo <<<END a END; }
Output of the above example in PHP 7.3:
PHP Parse error: Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
The closing identifier for the body string is not required to be followed by a semicolon or newline. For example, the following code is allowed as of PHP 7.3.0:
Example #4 Continuing an expression after a closing identifier
<?php $values = [<<<END a b c END, 'd e f']; var_dump($values);
Output of the above example in PHP 7.3:
array(2) { [0] => string(11) "a b c" [1] => string(5) "d e f" }
Warning
If the closing identifier was found at the start of a line, then regardless of whether it was a part of another word, it may be considered as the closing identifier and causes a ParseError.
Example #5 Closing identifier in body of the string tends to cause ParseError
<?php $values = [<<<END a b END ING END, 'd e f'];
Output of the above example in PHP 7.3:
PHP Parse error: syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6
To avoid this problem, it is safe for you to follow the simple rule: do not choose the closing identifier that appears in the body of the text.
Warning
Prior to PHP 7.3.0, it is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;
). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It’s also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is n
on UNIX systems, including macOS. The closing delimiter must also be followed by a newline.
If this rule is broken and the closing identifier is not «clean», it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.
Example #6 Invalid example, prior to PHP 7.3.0
<?php class foo { public $bar = <<<EOT bar EOT; } ?>
Example #7 Valid example, even if prior to PHP 7.3.0
<?php class foo { public $bar = <<<EOT bar EOT; } ?>
Heredocs containing variables can not be used for initializing class properties.
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
Example #8 Heredoc string quoting example
<?php $str = <<<EOD Example of string spanning multiple lines using heredoc syntax. EOD; class foo { var $foo; var $bar; function __construct() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<EOT My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': x41 EOT; ?>
The above example will output:
My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital
It is also possible to use the Heredoc syntax to pass data to function arguments:
Example #9 Heredoc in arguments example
<?php var_dump(array(<<<EOD foobar! EOD )); ?>
It’s possible to initialize static variables and class properties/constants using the Heredoc syntax:
Example #10 Using Heredoc to initialize static values
<?php function foo() { static $bar = <<<LABEL Nothing in here... LABEL; } class foo { const BAR = <<<FOOBAR Constant example FOOBAR; public $baz = <<<FOOBAR Property example FOOBAR; } ?>
The opening Heredoc identifier may optionally be enclosed in double quotes:
Example #11 Using double quotes in Heredoc
<?php echo <<<"FOOBAR" Hello World! FOOBAR; ?>
Nowdoc
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]>
construct, in that it declares a block of text which is not for parsing.
A nowdoc is identified with the same <<<
sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'
. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
Example #12 Nowdoc string quoting example
<?php echo <<<'EOD' Example of string spanning multiple lines using nowdoc syntax. Backslashes are always treated literally, e.g. \ and '. EOD;
The above example will output:
Example of string spanning multiple lines using nowdoc syntax. Backslashes are always treated literally, e.g. \ and
Example #13 Nowdoc string quoting example with variables
<?php class foo { public $foo; public $bar; function __construct() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<'EOT' My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': x41 EOT; ?>
The above example will output:
My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': x41
Example #14 Static data example
<?php class foo { public $bar = <<<'EOT' bar EOT; } ?>
Variable parsing
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.
The complex syntax can be recognised by the curly braces surrounding the expression.
Simple syntax
If a dollar sign ($
) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.
<?php $juice = "apple"; echo "He drank some $juice juice.".PHP_EOL; echo "He drank some juice made of $juices."; echo "He drank some juice made of ${juice}s."; ?>
The above example will output:
He drank some apple juice. He drank some juice made of . He drank some juice made of apples.
Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]
) marks the end of the index. The same rules apply to object properties as to simple variables.
Example #15 Simple syntax example
<?php $juices = array("apple", "orange", "koolaid1" => "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 = "John Smith"; public $jane = "Jane Smith"; public $robert = "Robert Paulsen"; public $smith = "Smith"; } $people = new people(); echo "$people->john drank some $juices[0] juice.".PHP_EOL; echo "$people->john then said hello to $people->jane.".PHP_EOL; echo "$people->john's wife greeted $people->robert.".PHP_EOL; echo "$people->robert greeted the two $people->smiths."; ?>
The above example will output:
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 .
As of PHP 7.1.0 also negative numeric indices are supported.
Example #16 Negative numeric indices
<?php $string = 'string'; echo "The character at index -2 is $string[-2].", PHP_EOL; $string[-3] = 'o'; echo "Changing the character at index -3 to o gives $string.", PHP_EOL; ?>
The above example will output:
The character at index -2 is n. Changing the character at index -3 to o gives strong.
For anything more complex, you should use the complex 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. The expression is written the same way as it would appear outside the string, and then wrapped in {
and }
. Since {
can not be escaped, this syntax will only be recognised when the $
immediately follows the {
. Use {$
to get a literal {$
. Some examples to make it clear:
<?php error_reporting(E_ALL); $great = 'fantastic'; echo "This is { $great}"; echo "This is {$great}"; echo "This square is {$square->width}00 centimeters broad."; echo "This works: {$arr['key']}"; echo "This works: {$arr[4][3]}"; echo "This is wrong: {$arr[foo][3]}"; echo "This works: {$arr['foo'][3]}"; echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of $object->getName(): {${$object->getName()}}"; echo "This is the return value of getName(): {getName()}"; echo "C:folder{$great}.txt" echo "C:\folder\{$great}.txt" ?>
It is also possible to access class properties using variables within strings using this syntax.
<?php class foo { var $bar = 'I am bar.'; } $foo = new foo(); $bar = 'bar'; $baz = array('foo', 'bar', 'baz', 'quux'); echo "{$foo->$bar}n"; echo "{$foo->{$baz[1]}}n"; ?>
The above example will output:
Note:
The value accessed from functions, method calls, static class variables, and class constants inside
{$}
will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}
) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
<?php error_reporting(E_ALL); class beers { const softdrink = 'rootbeer'; public static $ale = 'ipa'; } $rootbeer = 'A & W'; $ipa = 'Alexander Keith's'; echo "I'd like an {${beers::softdrink}}n"; echo "I'd like an {${beers::$ale}}n"; ?>
String access and modification by character
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.
Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted
E_NOTICE
for reading (yielding an empty string) andE_WARNING
for writing (leaving the string untouched).
Note: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
Warning
Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_WARNING
. Only the first character of an assigned string is used. As of PHP 7.1.0, assigning an empty string throws a fatal error. Formerly, it assigned a NULL byte.
Warning
Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.
Note: As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal error. Formerly, the empty string was silently converted to an array.
Example #17 Some string examples
<?php $str = 'This is a test.'; $first = $str[0]; $third = $str[2]; $str = 'This is still a test.'; $last = $str[strlen($str)-1]; $str = 'Look at the sea'; $str[strlen($str)-1] = 'e'; ?>
String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown.
Example #18 Example of Illegal String Offsets
<?php $str = '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 above example will output:
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)
Note:
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using
[]
or{}
silently returnsnull
.
Note:
Characters within string literals can be accessed using
[]
or{}
.
Note:
Accessing characters within string literals using the
{}
syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
I’m using PHP heredoc but I get an error
When I checked, «EOT;» which is a signal that here is the here document at the end in here document
It was said that an error would occur if the fault is deeper than the content of the here document.
No matter how much I improve, I get an error. .. ..
Reference site
$escape =<<<EOT
<p>Birthday</p>
<select name="year">
<option value="null">AD</option>
<option value="1900">1900</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2030">2030</option>
</select>
<select name="month">
<option value="null">month</option>
<option value="1">January</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="day">
<option value="null">day</option>
<option value="1">1 day</option>
<option value="18">18 days</option>
<option value="19">19th day</option>
</select>
<br>
<p>Gender</p>
<select name="sex">
<option value="null">gender</option>
<option value="male">male</option>
<option value="woman">woman</option>
</select>
<input type="submit" value="complete">
</form>
EOT;
echo $escape;
}catch(PDOException $e){
print "display error";
print "<br>";
die($e->getMessage());
}
What I want to do
<?php
$a =<<<EOT
Implementation contents
EOT;
?>
Is it possible only with the code below
<?php
$a =<<<EOT
Implementation contents
EOT;
?>