As we know from the last lesson, strings are sequences of characters. Before we can use a string, we have to create it! We can create it by different ways .
The easiest way to define a string is to close it in single quotes $string = 'value' , and all characters in quotes will perceived as character.
'value' ; echo $string; // output value $var = 15; $string = '$var' ; echo $string; // output $var$string =
If we try to use (') character in single quotes, it will not output character, as it close the first quotes, and returns error. In order to use (') or / characters in single quote we must use it with backslash (\).
'val'ue' ' ; echo $string; // wrong code, as middle quotes is closed the first quotes and ue is undefined $string = 'val\'ue' ; echo $string; // output val\'ue $string = 'val\\ue' ; echo $string; // output val\\ue$string =
We can also define string by double quotes ( $string = "value") .
Strings defined by double quotes are recognized by php, and in output return value of variable .
"value" ; echo $string; // output value $value = 10 ; $string = "value of variable is $string"; echo $string; // output value of variable is 10 $string = 'This is /n new line' ; echo $string; // output This is // new line$string =
In this case, Php automatically recognizes a lot of special characters.
Another way to define strings is to use heredoc-syntax. It will start with (<<< ) keyword, then there must be specific ID, then string and in the end the same identifier to close the inserting.
The closing identifier must begin from the first column of the line.
Specify id must match letter, integer or underscore, and must start with letter or underscore.
"heredoc-syntax"; $str = <<<IDNAME This is , example of string, using $var. IDNAME echo $str ; // This is , example of string, using heredoc-syntax.$var =
Closing identifier doesn't contain any other characters, except a semicolon (;). This means that there can not be any spaces or tabs before or after the semicolon.
As we can see the definition of heredoc-syntax is similar with the definition of double quotes, that is all variables and special characters, are outputs by value.
Another way to define string, is Nowdoc .
Nowdoc like a heredoc, but it does not screen the symbols.
This is ideal for the implementation of PHP-code or other large blocks of text without having to screening.
Nowdoc defines the same sequence that is used in the heredoc, but follows its identifier enclosed in single quotes, for example, <<< 'EOT' .
"example"; $str = <<<'IDNAME' This is , example of string, using $var. IDNAME echo $str ; // This is , example of string, using $var.$var =
Nowdoc support was add by PHP 5.3.0
Php have a lot of functions for manipulate string, and we will learn about them in our next lessons.