In this tutorial, you shall be introduced to Strings in PHP, how to define string literals, how to print string values, how to create strings from different using characters, or numeric sequences, etc., with examples.
PHP Strings
In PHP, String is a sequence of characters.
Each character in a string is of size byte. Hence, PHP supports only 256-character set.
You can specify a string using single or double quotes. But each of these have their own meaning in interpreting some of the escaped characters. We will learn in detail.
Single Quoted Strings
To define a string in PHP, you can write the sequence of characters enclosed in single quotes.
Following is an example where we initialized a variable with a string using single quotes.
<?php
$string = 'Hello World!';
echo $string;
?>
Single quoted string does not interpret escaped sequences like \n, \r, \t, etc. But there is only one exception that you can escape a single quote. So, any backslash character that comes in a single quoted string is considered as just another character, except for the backslash followed by a single quote.
In the following program, we have demonstrated this behavior.
PHP Program
<?php
$string1 = 'Hello\' World!';
echo $string1;
echo '<br>';
$string2 = 'Hello\n\t World!';
echo $string2;
?>
Output
