Page 112 - Beginning PHP 5.3
P. 112
Part II: Learning the Language
Creating and Accessing Strings
As you learned in Chapter 3 , creating a string variable is as simple as assigning a literal string value to a
new variable name:
$myString = ‘hello‘;
In this example, the string literal ( hello ) is enclosed in single quotation marks ( ‘ ). You can also use
double quotation marks ( “ ), as follows:
$myString = “hello”;
Single and double quotation marks work in different ways. If you enclose a string in single quotation
marks, PHP uses the string exactly as typed. However, double quotation marks give you a couple of
extra features:
❑ Any variable names within the string are parsed and replaced with the variable ’ s value
❑ You can include special characters in the string by escaping them
Here are some examples to make these differences clear:
$myString = ‘world’;
echo “Hello, $myString! < br/ > ”; // Displays “Hello, world!”
echo ‘Hello, $myString! < br/ > ’; // Displays “Hello, $myString!”
echo “ < pre > Hi\tthere! < /pre > ”; // Displays “Hi there!”
echo ‘ < pre > Hi\tthere! < /pre > ’; // Displays “Hi\tthere!”
With the “ Hello, world! ” example, notice that using double quotes causes the $myString variable name
to be substituted with the actual value of $myString . However, when using single quotes, the text
$myString is retained in the string as - is.
With the “Hi there!” example, an escaped tab character ( \t ) is included within the string literal. When
double quotes are used, the \t is replaced with an actual tab character; hence the big gap between Hi
and there! in the output. The same string enclosed in single quotes results in the \t characters being
passed through intact.
Here ’ s a list of the more common escape sequences that you can use within double - quoted strings:
S equence M eaning
\n A line feed character (ASCII 10)
\r A carriage return character (ASCII 13)
\t A horizontal tab character (ASCII 9)
\v A vertical tab character (ASCII 11)
\f A form feed character (ASCII 12)
\\ A backslash (as opposed to the start of an escape sequence)
\$ A $ symbol (as opposed to the start of a variable name)
\” A double quote (as opposed to the double quote marking the end of a string)
74
9/21/09 8:53:39 AM
c05.indd 74 9/21/09 8:53:39 AM
c05.indd 74