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'; ?>
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 Mac OS X. 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.
Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.
<?php class foo { public $bar = <<<EOT bar EOT; } ?>
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.
<?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 foo() { $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:
<?php var_dump(array(<<<EOD foobar! EOD )); ?>
As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax:
<?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; } ?>
Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:
<?php echo <<<"FOOBAR" Hello World! FOOBAR; ?>
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.
<?php $str = <<<'EOD' Example of string spanning multiple lines using nowdoc syntax. EOD; /* More complex example, with variables. */ class foo { public $foo; public $bar; function foo() { $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
<?php class foo { public $bar = <<<'EOT' bar EOT; } ?>
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."; ?>
He drank some apple juice. He drank some juice made of .
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.
<?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 .
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be 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}"; 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()}"; ?>
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"; ?>
I am bar. I am bar.
Note:
Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed 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"; ?>
<?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'; ?>
As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.
<?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'])); ?>
Output of the above example in PHP 5.3:
string(1) "b" bool(true) string(1) "b" bool(true) string(1) "a" bool(true) string(1) "b" bool(true)
Output of the above example in PHP 5.4:
string(1) "b" bool(true) Warning: Illegal string offset '1.0' in /tmp/t.php on line 7 string(1) "b" bool(false) Warning: Illegal string offset 'x' in /tmp/t.php on line 9 string(1) "a" bool(false) string(1) "b" bool(false)
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX
), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
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). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
<?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?>
For more information on this conversion, see the Unix manual page for strtod(3).
To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:
<?php echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n"; ?>
Please login to continue.