PHP Strings – Ways to Create Strings in PHP
Working with strings is a common task in PHP or in other programming languages. Strings are one of the most important data types in PHP, along with Boolean, integer, float, array, and object.
In PHP, a string is a sequence of characters enclosed in single or double quotes. It is mainly used to store textual information, such as names, messages, and HTML content.
Strings are scalar (primitive) data types in PHP, meaning that they hold only single value (i.e. a sequence of characters) at a time. They are not compound (complex) data types, such as arrays or objects where you can store multiple values.
Strings cannot be broken down into smaller primitive types unlike arrays, which can be split into smaller elements, such as primitive or other arrays.
By default, PHP strings are byte-based, not character-based. Each character occupies 1 byte (8 bits) in single-byte encoding like ASCII. This means functions like strlen() count bytes rather than characters. PHP does not support native Unicode characters or sequences unlike Python 3 or JavaScript where strings are Unicode by default.
Ways to Create Strings in PHP
There are mainly four ways to create strings in PHP. They are as follows:
- Single quotes
- Double quotes
- Heredoc Syntax
- Nowdoc Syntax
Single Quotes
In PHP, you can create a string by enclosing in a single quotation marks (‘ ‘). This is the simplest form to create strings in PHP. An example of creating a string within a single quotation marks is as:
<?php
$str = 'This is a single-quoted string.';
echo $str;
?>
Output: This is a single-quoted string.
When you define a string using single quotes (‘ ‘), PHP does not parse or interpret the contents of the string. Variables inside the string are treated as plain text, not as actual variable references.
Example 1:
<?php
$name = 'John'; // Single quotes.
echo 'Hello $name';
?>
Output: Hello $name
In this example, we have created a string variable named $name. When we reference this variable within a single-quoted string, PHP treats it as plain text, not as a variable. This is because single quotes do not parse variables. Therefore, it outputs the literal characters $name instead of the value stored in the variable.
Escape Sequences Supported in Single-Quoted Strings in PHP
In PHP, strings enclosed within single quotation marks support only a limited set of escape sequences, such as
- \\ (to insert a literal backslash).
- \’ (to insert a single quote inside a single-quoted string).
All other escape sequences, such as \n (newline) or \t (tab), are not interpreted in single-quoted strings because they are treated as plain text. Look at the below following example code.
Example 2:
<?php
echo 'It\'s a test.';
echo ' This is a backslash: \\.';
echo ' Line break:\nNew line';
?>
Output: It's a test. This is a backslash: \. Line break:\nNew line
In this example, the escape sequences, such as \’ and \\ work as expected. But the escape sequence \n is not interpreted. It’s just printed as a text literally.
So, single-quoted strings in PHP are useful when you need to maintain the exact textual content without any variable substitution or extensive escape sequence interpretation in PHP code.
Double Quotes
In PHP, you can also create a string by enclosing it in double quotation marks (‘” “). This is another simplest way to create strings in PHP. One example of creating a string using double quotes is:
Example 3:
<?php
// Creating a string in double-quotes.
$name = "Saanvi";
echo "Hello, $name";
?>
Output: Hello, Saanvi
In this example, we have created a string in double-quotation marks. As you can see the variable $name is replaced with “Saanvi” inside the string because strings enclosed within double-quotation marks (” “) are parsed by the PHP interpreter.
This means that when you place a variable inside double quotes, PHP will automatically replace it with its stored value. This behavior is known as string or variable interpolation. String interpolation is the process of embedding variables within a string. Look at another example below.
Example 4:
<?php
$game = "cricket";
echo "I like to play $game.\n";
// You can also use curly braces for clarity.
echo "I like to play {$game}."
?>
Output: I like to play cricket. I like to play cricket.
Supported Escape Sequences in Double-Quoted Strings
In PHP, when you create a string using double quotation marks (” “), the interpreter also parses all common escape sequences, such as ‘”‘ to represent a double quotation marks, ‘\\’ for a literal backslash, ‘\n’ for a newline, ‘\r’ for a carriage return, and many others.
These escape sequences are interpreted and converted with their corresponding special characters when string is evaluated. Let’s take an example on it.
Example 5:
<?php
$name = "Saanvi";
echo "Hello, \"$name\"!\nWelcome to PHP.\n";
echo "Here's a tab:\tDone.\n";
echo "This is a backslash: \\\n";
echo "Dollar: \$100";
?>
Output: Hello, "Saanvi"! Welcome to PHP. Here's a tab: Done. This is a backslash: \ Dollar: $100
Note that double-quoted strings in PHP automatically expand variables and interpret escape characters. However, its performance is slightly slower than single-quotes.
Heredoc and Nowdoc Strings in PHP
In addition to single-quoted and double-quoted strings, PHP provides two special syntaxes for defining multi-line strings: Heredoc and Nowdoc.
These syntaxes are useful when you are dealing with large blocks of text, HTML templates, SQL queries, or strings that span multiple lines. Let’s understand both syntaxes one by one with examples.
Heredoc
Heredoc is a powerful mechanism in PHP to create multi-line strings. It works similarly to double-quoted strings. It enhances code clarity, readability, and maintainability. Heredoc supports both variable interpolation and escape sequences.
The basic syntax of Heredoc begins with three less than characters (<<<) followed by an identifier of your choice and ends with the same identifier followed by the semicolon (;). The general syntax is as:
$str = <<<IDENTIFIER
// Multi-line strings
IDENTIFIER;
In the above syntax, <<<IDENTIFIER is opening tag and IDENTIFIER; is closing tag. IDENTIFIER is any user-defined label or identifier which is conventionally uppercase. For example, EOD, HTML, SQL, etc.
The closing tag must be alone on a new line with no indentation. It must match the opening identifier exactly. It must end with a semicolon (;). No white space is allowed before the closing identifier. You must use the closing identifier to denote the end of the string.
Example 6:
<?php
$name = "Saanvi \n";
$address = <<<ADDR
Shiv shakti Complex,
Joraphatak Road,
Dhanbad.
ADDR;
echo $name;
echo $address;
?>
Output: Saanvi Shiv shakti Complex, Joraphatak Road, Dhanbad.
Example 7: Using variable interpolation
<?php
$city = "Dhanbad";
$address = <<<ADDR
Shiv shakti Complex,
Joraphatak Road,
$city.
ADDR;
echo $address;
?>
Output: Shiv shakti Complex, Joraphatak Road, Dhanbad.
Note that you can indent the opening tag <<<IDENTIFIER, but the closing one cannot. PHP 7.3+ allows optional white space before the semicolon but not before the identifier.
Example 8:
<?php
$name = "Alice";
$str = <<<EOD
Hello, $name!\n
This is a Heredoc example:
- Supports "quotes" and escapes (\t for tab).
- Spans multiple lines without concatenation.
EOD;
echo $str;
?>
Output: Hello, Alice! This is a Heredoc example: - Supports "quotes" and escapes ( for tab). - Spans multiple lines without concatenation.
Practical Examples
Example 9: HTML Templates
<?php
$title = "Home";
echo <<<HTML
<!DOCTYPE html>
<html>
<head><title>$title</title></head>
<body>...</body>
</html>
HTML;
?>
Example 10: SQL Queries
$query = <<<SQL
SELECT * FROM users
WHERE id = $id
SQL;
Nowdoc
Similar to heredoc, nowdoc provides a clean way to write non-interpreted, multi-line strings in PHP. However, it is defined using single quotes around the identifier, not around the string content itself. Nowdoc strings differ from heredoc in that they treat the entire block as literal text. They do not support variable interpolation and escape sequence parsing.
Therefore, you can use nowdoc particularly when you want to preserve the exact content of the string, including variables names and escape characters, without any parsing or interpretation within the string.
This feature makes Nowdoc a straightforward and reliable method for writing static or unaltered textual data in your PHP code—such as code snippets, configuration examples, or templates that should not be evaluated. The general syntax to define nowdoc strings in PHP is as follows:
$text = <<<'IDENTIFIER'
// Multi-line strings.
IDENTIFIER;
In the above syntax of nowdoc, <<<‘IDENTIFIER’ is an opening tag which starts the nowdoc block. Note that you must enclose the single quotes around the IDENTIFIER.
The closing identifier (IDENTIFIER;) must appear on its own line, with no indentation, spaces, or tabs before or after it. A semicolon (;) is required immediately after the closing identifier to properly terminate the statement.
Example 11:
<?php
$name = "John";
$text = <<<'DELIMITER'
This is a Nowdoc string.
Variables like $name and escape sequences like \n are not parsed.
DELIMITER;
echo $text;
?>
Output: This is a Nowdoc string. Variables like $name and escape sequences like \n are not parsed.
Example 12:
<?php
$str = <<<'CODE'
$var = "Hello PHP"; // This $var remains literal.
echo \$var; // Even escaped \$ stays literal.
CODE;
echo $str;
?>
Output: $var = "Hello PHP"; // This $var remains literal. echo \$var; // Even escaped \$ stays literal.
Heredoc vs. Nowdoc Strings
Feature | Heredoc | Nowdoc |
---|---|---|
Variable interpolation | Yes | No |
Escape sequences | Supported | Not supported |
Quote handling | Handles quotes | Handles quotes |
Best for | Dynamic multi-line text | Literal multi-line text |
Strings are a fundamental data type of PHP programming, which allows you to handle text, dynamic content, and user interaction with ease. PHP offers a variety of ways to define and manipulate strings, including single-quoted, double-quoted, Heredoc, and Nowdoc. Each way has its own best uses.
Single-quoted strings are the best suited for simple, literal text where no variable parsing or escape sequences are needed. On the other hand, double-quoted strings are ideal when you need variable interpolation and support for special escape sequence characters.
For larger blocks of text or templates, you can use Heredoc syntax, while Nowdoc syntax gives you to handle static or unaltered textual content. I hope that you will have understood the basic concepts of PHP strings and practiced all examples based on them.