Strings in PHP is a combination or sequence of characters, numbers and special symbols. In PHP, strings can be represented in
- Double quotes
- Single quotes
- Heredoc
- Newdoc
String in Double quote
<?php
$name = "PHP";
echo $name;
?>
String in Single quote
<?php
$name = 'PHP string';
echo $name;
?>
Multiline string
Both single quote or double quotes can be used to create multiline string.
<?php
$text = 'PHP
string
Tutorial...';
echo $text;
?>
Heredoc
Heredoc allows to create a string without single or double quotes, and also allows to use your own string identifier.
Syntax
<?php
$text = <<<IDENTIFIER
IDENTIFIER;
?>
Heredoc uses three less than symbol and IDENTIFIER and a newline and Ends with IDENTIFIER and semicolon. Start identifier and End identifier name must be same.
Space is allowed between <<< IDENTIFIER.
Example
<?php
$age = 20;
$text = <<<MYTEXT
Hello this is Heredoc example,
You can use 'single quote' and "Double quote"
in Heredoc.
Variables are also allowed $age value is printed with the string output.
You can add as many line as you can.
MYTEXT;
?>
<<<identifier, Here you can create your own identifier like in above example <<<MYTEXT, and identifier should ends with same name MYTEXT;
Heredoc has following advantages
- Single quotes and double quotes can be used inside Heredoc.
- Multiline strings can be used.
- Variable can also be used with heredoc string. and it outputs variable value in string.
Nowdoc
Nowdoc is similar to Heredoc with a small difference, ‘IDENTIFIER’ must be inside single quote and not able to print or outputs variables value inside string.
Syntax
<?php
$text = <<<'IDENTIFIER'
IDENTIFIER;
?>