Escape sequences are used for escaping a character during string parsing. It is also used for giving special meaning to represent line breaks, tabs, alerts and more.
The escape sequences are interpolated into strings enclosed by double quotations or heredoc syntax. If a string is within the single quotes or in nowdocs, then the escape sequence will not work to get the expected result. In a previous tutorial, we have seen variable interpolation.
Escape sequences are started with the escaping character backslash (\) followed by the character which may be an alphanumeric or a special character. If it is an alphanumeric character, it gives special meaning to represent the line breaks \n, carriage return \r and more.
If it is a special character, then it will be considered as it is during the string parsing. For example, if we interpolate \$var into a string then it will be taken as $var. Without the escaping character (\), the $var PHP variable is parsed to get its value.
This code shows a simple PHP example program to distinguish the behavior of the escape sequences with alphanumeric and non-alphanumeric characters.
In this example, I used the escape sequence \n to add a line break after label and I have used \\ to escape \ character and print it to the browser.
<?php echo "PHP Escape Sequences:\n Backslash \\ is used as an escaping character."; ?>
In this section, I have listed some of the widely used escape sequences and describe how they are used to escape the special character or to give meaning by combining them with some alphanumeric characters.