PHP how to make a string

Learn how to create a string in PHP with an example. Find out the different ways to define and format strings and how to manipulate them.

Creating a String in PHP

A string is a sequence of characters, used to store and represent text-based information. PHP offers a variety of ways to create a string.

Single Quotes

One of the most straightforward and commonly used string creation methods is to wrap the string in single quotes:

$string = 'This is a string.';

When using single quotes, it's important to note that any variables enclosed within the string will not be parsed by PHP — meaning that PHP won't attempt to interpret the variable's value and include it in the output. This is because the single quotes are used to literally define the contents of the string.

Double Quotes

Double quotes work similarly to single quotes, but they allow the use of variables within the string, as they are parsed by PHP:

$name = 'John';
$string = "Hello $name"; // outputs Hello John

When using double quotes, you must also escape any double quote characters within the string itself, using the backslash character:

$string = "This is "my" string"; // outputs This is "my" string

Nowdoc Syntax

The nowdoc syntax is a way of defining a string that is completely literal, meaning that all variables, escape sequences and special characters within the string will be printed, rather than parsed by PHP.

$string = <<<EOD
This is a string.
It will not parse any variables or escape sequences.
EOD;

The nowdoc syntax is commonly used when defining large blocks of text, such as HTML or SQL, as it eliminates the need to escape any characters within the string.

Heredoc Syntax

The heredoc syntax works similarly to the nowdoc syntax, but it allows the use of variables within the string, as it is parsed by PHP:

$name = 'John';
$string = <<<EOD
Hello $name
EOD;

// outputs Hello John

It's important to note that the heredoc syntax must end with the same identifier that was used to begin the string. In the example above, the identifier is EOD. If the identifier is not used, a parse error will occur.

String Concatenation

Finally, strings can be created by combining two or more strings together, using the concatenation operator (.):

$string1 = 'This is ';
$string2 = 'a string.';
$string = $string1 . $string2; // outputs This is a string.

Using this method, strings can be created from multiple variables, and the resulting string can be stored in the original variable.

As you can see, there are a variety of ways to create a string in PHP. Depending on the type of string being created, you can choose the method that best suits your needs.

Answers (0)