How To Work with Strings in PHP
How To Work with Strings in PHP

Tutorial

How To Work with Strings in PHP

PHPDevelopment

The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

Introduction

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.

Single and Double-Quoted Strings

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:

Output
Sammy 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 (\\\'). First \\ 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 (\')."
Output
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 (\').

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.

The \ 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.

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
  • \n for a new line
  • \t for 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.

Creating and Viewing the Output of Strings

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 echo function:

$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.";

The $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.

Output
Name 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.

String Concatenation

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 Chews wisely.:

Output
What do sharks do when they have a big choice to make? Chews wisely.

A second way to concatenate strings is to use the . operator.

Let’s combine the strings "Sammy" and "Shark" together with concatenation through an echo statement:

echo "Sammy" . "Shark";

This code uses the . operator to combine the "Sammy" string and the "Shark" string without a space in between.

Output
SammyShark

If you would like whitespace between the two strings, you must include the whitespace within a string, like after the word Sammy:

echo "Sammy " . "Shark";
Output
Sammy Shark

You cannot use concatenation to combine a string with an integer:

echo "Sammy" . 27;

This will produce an error:

Output
Parse 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;
Output
Sammy27

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.

Updating 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 variable:

$my_name = "Sammy";
echo $my_name . "\n";
$my_name = "Shark";
echo $my_name;
Output
Sammy Shark

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 "Shark".

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 $my_name is Sammy Shark.

Output
Sammy Shark

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 $my_name is Sammy Shark.

Output
Sammy Shark

Overwriting, appending, and prepending give us the ability to make changes and build the strings required for our applications.

Whitespace in Strings

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 Output
Sammy 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 Output
Sammy 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.

Conclusion

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:

  1. Pay special attention to quotes within your strings.
  2. Use concatenation to combine your strings.
  3. Use variables to make your strings reusable.

If you would like to read more about PHP, check out the PHP topic page.

Creative Commons License