The Strings in PHP
Strings are the combination of characters. e.g. “Strings are supported in PHP”.
In this chapter, we will give you examples of creating, using and important functions associated with strings.
Creating PHP string
Following are examples of how you can create strings:
$str1 = “Strings are enclosed in double quotes”;
$str_0 = “”; // A string can contain 0 character
- You may enclose strings in double quotes e.g. “”.
- You can use single quotes to enclose strings as well.
e.g. $str1 = ‘This string is enclosed in single quotes’;
The difference between single and double quote string is the double-quoted strings will replace variables inside the strings to their values. Also, the double-quoted strings interpret certain character sequences.
See the following example:
$var_name = “name”;
$checkstr = ‘It will not print $var_name!\n’;
$checkstr = “It will print $var_name!”;
Following will be output
It will not print $var_name!
It will print name
In the above code, you can see the strings are created by using the single and double quotes. Two string variables are declared and assigned the values. After that, the print statement is used to display those string values. As mentioned, while using the double quotes in
After that, the print statement is used to display those string values. As mentioned, while using the double quotes in a string, you can use variables inside it. The variables will be replaced by its values when you display by using the print or echo statements of PHP.
Note, there is no specific limits in lengths of strings.
The escape sequence
Strings that are enclosed in double quotes will see the following characters, also known as the escape sequence, as described below:
- n means adding a new line.
- r meant to be replaced by the carriage-return character.
- t If used in a string, it will be replaced by the tab character.
- $ If you need to use a $ sign in a string then use it.
- ” means a single double-quote (“).
- \ means to add a single backslash ().
Now, as you have gone through how to create and display the strings, let us explore a few important functions provided by PHP. Click on any function below to go into detail of that function.