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 in 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.
$string = 'value' ; echo $string; // output value $var = 15; $string = '$var' ; echo $string; // output $var
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 (\).
$string = 'val'ue' ' ; echo $string; // wrong code, as middle quotes are closed the first quotes and ue is undefined $string = 'val\'ue' ; echo $string; // output val\'ue $string = 'val\\ue' ; echo $string; // output val\\ue
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 .
$string = "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
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 a letter or underscore.
$var = "heredoc-syntax"; $str = <<<IDNAME This is , example of string, using $var. IDNAME echo $str ; // This is , example of string, using heredoc-syntax.
Closing identifier doesn't contain any other characters, except a semicolon (;). It 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 to the description 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 screen.
Nowdoc defines the same sequence that is used in the heredoc, but follows its identifier enclosed in single quotes, for example, <<< 'EOT' .
$var = "example"; $str = <<<'IDNAME' This is , example of string, using $var. IDNAME echo $str ; // This is an example of string, using $var.
Nowdoc support was add by PHP 5.3.0
Php have a lot of functions for manipulating string, and we will learn about them in our next lessons.