Chapter 4. Strings
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 \110\145\154\154\157\40\127\157\162\154\144\41
).1 Every element of data read or written by a PHP application is represented as a string.
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 shows single-quoted strings along with their corresponding printed output.
Note
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 ...