Strings are one of the fundamental building blocks of data in PHP. Each string represents an ordered sequence of bytes. Strings can range from human-readable sections of text - like “To be or not to be” - to sequences of raw bytes encoded as integers - such as “1101451541541574012715716215414441”.1 Every element of data read or written by a PHP application is represented as strings.
In PHP, strings are typically encoded as ASCII values, although you can convert between ASCII and other formats (like UTF-8) as necessary. Strings can contain null bytes when needed, and are essentially limitless in terms of storage so long as the PHP process has adequate memory available.
The most basic way to create a string in PHP is with single quotes. Single-quoted strings are treated as literal statements - there are no special characters or any kind of interpolation of variables. To include a literal single quote within a single-quoted string, you must escape that quote by prefixing it with a backslash - for example '
. In fact, the only two characters that need to be - or even can be - escaped are the single quote itself or the backslash. Example 4-1 provides examples of single-quoted strings along with their corresponding, printed output.
Variable interpolation is the practice of referencing a variable directly by name within a string and letting the interpreter replace the variable with its value at runtime. Interpolation allows for more flexible strings as you can write a single string but dynamically replace some of its contents to fit the context of where it’s being used in code.
'Hello, world!'
;
// Hello, world!
'You've only got to escape single quotes and the \ character.'
;
// You've only got to escape single quotes and the character.
'Variables like $blue are printed as literals.'
;
// Variables like $blue are printed as literals.
'1101451541541574012715716215414441'
;
// 1101451541541574012715716215414441
More complicated strings might need to interpolate variables or reference special characters, like a newline or tab. For these more complicated use cases, PHP requires the use of double quotes instead and allows for various escape sequences as shown in Table 4-1.
Escape sequence | Character | Example |
---|---|---|
|
Newline |
|
|
Carriage return |
|
|
Tab |
|
|
Backslash |
|
|
Dollar sign |
|
|
Double quote |
|