A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. All written communication is made up of strings. As such, they are fundamental to any programming language.
In this article, you will learn how to create and view the output of strings, how to use escape sequences, how to concatenate strings, how to store strings in variables, and the rules of using quotes, apostrophes, and newlines within strings in PHP.
You can create a string in PHP by enclosing a sequence of characters in either single or double quotes. PHP will actually interpret the following strings differently:
'This is a string in single quotes.'
"This is a string in double quotes."
Before output, double-quoted strings will evaluate and parse any variables or escape sequences within the string. Single-quoted strings will output each character exactly as specified. The exception for single-quoted strings is a single quote (and backslash when needed).
If you were to
echo this string in PHP:
'Sammy says: "This string\'s in single quotes." It required a backslash (\) before the apostrophes (\\\'), but do not use (\") with the double quotes.'
It would return this output:
OutputSammy says: "This string's in single quotes." It required a backslash (\) before the apostrophes (\'), but do not use (\") with the double quotes.
If you don’t include a backslash before the apostrophe in the single-quoted string, PHP will end the string at that point, which will cause an error. Since you’re using single quotes to create our string, you can include double quotes within it to be part of the final string that PHP outputs.
If you want to render the
\' sequence, you must use three backslashes (
\\ to render the backslash itself, and then
\' to render the apostrophe. The sequence
\" is rendered exactly as specified.
"Sammy says: \"This string's in double quotes.\" It requires a backslash (\) before the double quotes (\\\"), but you MUST NOT add a backslash before the apostrophe (\')."
OutputSammy says: "This string's in double quotes." It requires a backslash (\) before the double quotes (\"), but you MUST NOT add a backslash before the apostrophe (\').
As with the single-quoted string, if a backslash is not included before the double quotes in the double-quoted string, PHP will end the string at that point, which will cause an error. Since the double-quoted string is not ended with a single quote, you add the apostrophe directly to a double-quoted string. A double-quoted string will output
\' with either a single or double backslash used with the apostrophe.
To output the
\" sequence, you must use three backslashes. First
\\ to render the backslash itself, and then
\" to render the double quote. The sequence
\' is rendered exactly as specified.
\ is known as an escape character. Combined with a secondary character, it makes up an escape sequence. Now that you have an understanding of strings, let’s review escape sequences.
An escape sequence tells the program to stop the normal operating procedure and evaluate the following characters differently.
In PHP, an escape sequence starts with a backslash
\. Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.
Here are some common escape sequences for double-quoted strings:
\"for a double quote
\\for a backslash
\$to render a dollar sign instead of expanding the variable
\nfor a new line
\tfor a tab
Here is an example of how you can use these sequences in a string:
"\"What type of \$ do sharks use?\"\n\tSand dollars!"
Output"What type of $ do sharks use?" Sand dollars!
Using escape sequences gives us the ability to build any string required while including these special characters.
The most important feature of double-quoted strings is the fact that variable names will be expanded, giving you the value of the variable. You can use a variable to stand in for a string or use a string directly. You output the string by calling the
$my_name = "Sammy"; echo 'Name is specified using the variable $my_name.'; echo "\n"; // escape sequence for newline character echo "Hello, my name is $my_name. It's stored in the variable \$my_name.";
$my_name variable is created on the first line. On the second line, the
echo function is used to output a string in single quotes. Using the
$my_name variable within this single-quoted string displays the characters exactly as they are written, so we will see the variable name instead of its value.
On the fourth line, we use the
echo function again, but we are using double quotes this time. This time the variable is expanded to show the value in the first sentence. In the next sentence, there is a
\ before the
$ to explicitly tell the string to display a
$ character and not expand the variable.
OutputName is specified using the variable $my_name. Hello, my name is Sammy. It's stored in the variable $my_name.
Note: When string evaluation is not a concern, you may choose to use either single quotes or double quotes, but whichever you decide on, you should be consistent within a program. Single quotes may be marginally faster.
With an understanding of how to create and view the output of strings, let’s move on to see how you can manipulate strings.
Concatenation means joining strings together, end-to-end, to build a new string. In PHP, there are two main ways to concatenate a string.
The first is to include a string variable within a double-quoted string. This was shown in the previous step and in the following:
$answer = "Chews wisely."; echo "What do sharks do when they have a big choice to make? $answer";
Running this code will combine the string and the
$answer variable, which is set to
OutputWhat do sharks do when they have a big choice to make? Chews wisely.
A second way to concatenate strings is to use the
Let’s combine the strings
"Shark" together with concatenation through an
echo "Sammy" . "Shark";
This code uses the
. operator to combine the
"Sammy" string and the
"Shark" string without a space in between.
If you would like whitespace between the two strings, you must include the whitespace within a string, like after the word
echo "Sammy " . "Shark";
You cannot use concatenation to combine a string with an integer:
echo "Sammy" . 27;
This will produce an error:
OutputParse error: syntax error, unexpected '.27' (T_DNUMBER), expecting ';' or ',' in php shell code on line 1
If you put
"27" within quotes, it will evaluate as a string.
PHP is a loosely typed language, which means that it will try to convert the data it is given based on the request. If you set a variable to
27, when used in concatenation with a string, PHP will parse the variable as a string:
$my_int = 27; echo "Sammy" . $my_int;
You’ve covered the two main ways to concatenate, or combine, strings. Sometimes you may want to replace, or add to, the string completely. Next, let’s explore how PHP allows you to overwrite or update a string.
Normal variables in PHP are mutable, which means they can be changed or overwritten. Let’s explore what happens when you change the value for the
$my_name = "Sammy"; echo $my_name . "\n"; $my_name = "Shark"; echo $my_name;
First, the variable was set to
"Sammy" and displayed using
echo. Then it was set to
"Shark", overwriting the variable, so that when
echo was called a second time, it displayed the new value of
Instead of overwriting the variable, you can use the concatenating assignment operator
.= to append to the end of a string:
$my_name = "Sammy"; $my_name .= " Shark"; echo $my_name;
First, you set the
$my_name variable to
"Sammy", then used the
.= operator to add
" Shark" to the end of it. The new value for
To prepend to the beginning of a string, you would overwrite while using the original string:
$my_name = "Shark"; $my_name = "Sammy " . $my_name; echo $my_name;
This time, you first set the
$my_name variable to
"Shark", then used the
= operator to override the
$my_name variable with the new string
"Sammy ", combined with the previous value of the
$my_name variable, which before being overridden is
"Shark". The final value for
Overwriting, appending, and prepending give us the ability to make changes and build the strings required for our applications.
Because PHP does not care about whitespace, you can put as many spaces or line breaks within your quotes as you would like.
echo "Sammy The (silly) Shark";
TEXT OutputSammy The (silly) Shark
Keep in mind that HTML renders whitespace differently. New lines require a
<br> tag, so even though your source may have new lines, you will not see those new lines displayed on a web page. Similarly, no matter how many spaces there are in your code, only a single space is displayed between characters.
HTML OutputSammy The (silly) Shark
Clean and consistent use of whitespace is one of the best tools for making code more readable. Since PHP essentially ignores whitespace, you have a lot of flexibility that you can use to your advantage. An integrated development environment (IDE) can help you stay consistent with your code and use of whitespace.
Being able to control the way our strings are rendered is essential for communicating with an application’s end user. By updating and combining variables that include special characters, you can clearly communicate while keeping repetition to a minimum.
As you continue to work with strings, keep in mind these three aspects:
If you would like to read more about PHP, check out the PHP topic page.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
PHP is a popular server scripting language known for creating dynamic and interactive web pages.
Click here to Sign up and get $200 of credit to try our products over 60 days!