Strings are one of the eight data types that PHP supports. A string is a scalar type (it stores only a single piece of data) and is created by quoting any number or combination of characters (PHP does not have a separate character type). Strings in PHP are virtually unlimited in length.
The following are all strings in PHP:
- 'some text'
- "some more text"
- 'This is a sentence.'
- "00290"
- "January 26, 2007"
Note that PHP does not have a dedicated date or time type and that quoted numbers are, in fact, strings. Because PHP is weakly-typed, strings can easily be converted to numbers and vice versa.
Perhaps because strings are one of the most commonly used types in PHP, if not the most, they can be a frequent source of confusion and errors.
Assigning String Values
A string variable must abide by the same naming rules as any other variable in PHP. A variable can be assigned a string value using the assignment operator (=):
$name = 'Jon';
One string can be appended to another using the concatenation operator (.):
$name = 'Jon' . ' ' . 'Smith';
The concatenation and assignment operators can be used together as a shorthand:
$name = 'Jon';
$name .= ' Smith';
Single vs. Double Quotation Marks
The most important decision when it comes to when working with strings is whether you use single or double quotation marks. As stated already, you can use either, but there is a crucial difference between the two: Every character and variable within single quotation marks is treated literally (with one exception being the combination of \', see "Escaping Characters" below). The following code will not have the intended result of printing the variable's value:
$name = 'Jon';
echo 'Hello, $name';
That code will literally print "Hello, $name".
Conversely, characters and variables within double quotation marks will be interpreted. This code will print "Hello, Jon":
$name = 'Jon';
echo "Hello, $name";
(The image at right shows how NuSphere's PhpED syntax highlighter indicates whether a variable will be treated literally or not.)
Almost all of the special escape sequences (see below) also need to be used within double quotation marks.
Because of the interpretation that occurs with double-quoted strings, they are arguably less efficient than single-quoted strings. For most applications, the efficiency difference is irrelevant, though.
|