A string is a text that might contain characters, numbers or any special character. First of all, we will create a string. Either a string can be stored in a string variable or it can be directly output to a browser without using any variable. Consider the php example:
<html> <body><?php $str="String variable is being used"; echo $str; echo "Direct output"; ?></body> </html>
In the above example, we have used a string variable named, “str” that contains the string, “String variable is being used”. The first echo statement will display the string, “String variable is being used” and the second echo statement will display the string, “Direct output”.
The string is enclosed in double quotes. You can also use single quotes. Suppose you want to display an apostrophe in a string. Let’s see how you will do this.
echo ‘It’s a very good site to learn PHP!’;
echo ‘It won’t let you down!’;
Here we have used backslash() to escape the apostrophe. The output of the above PHP script in a web page will be:
It's a very good site to learn PHP! It won't let you down!
The output will appear in a single line because there was no <br> tag present. Let’s have a look at a few more escape sequences:
|Character ||Description |
|n ||Will add a new line |
|t ||Will add a tab |
|r ||Carriage return |
|$ ||A dollar sign will be displayed |
|“ ||Double quotes are displayed |
PHP String “heredoc”
Apart from the two ways to create a string that we discussed earlier, there is one more way to create a string-“heredoc”. It is used to create a multi-line string without the use of quotes. Have a look at the code given below:
<html> <body><?php $str=<<<TRY This is an example to demonstrate heredoc! TRY; echo $str; ?></body> </html>
Let’s have a look at this code. “str” is a string variable which stores multi-line string. It starts with <<< and an identifier. Here, we have used “TRY”. The “heredoc” ends with the identifier in the end followed by a semicolon. Remember that the closing sequence “TRY;” must be on a separate line that must not be indented. The output of the above script on a web page will again be in a single line due to the absence of <br> tag as shown below:
This is an example to demonstrate heredoc!