I l @ ve RuBoard |
A variable is a string if it consists of characters (some combination of letters , numbers , symbols, and spaces) enclosed within either a pair of single (') or double (") quotation marks. Strings can contain any combination of characters, including other variable names . Examples of valid strings values include: "Hello, world!" "Hello, $FirstName!" "1 1/4" 'Hello, world! How are you today?' "02.23.72" "1972" Notice how in the last example you took an integer and made it into a string by putting it within quotes. Essentially the string contains the characters "1972" whereas the number is equal to 1972. It's a fine distinction and one that will not matter in your code, as you could perform mathematical calculations with the string "1972" just as you could with the number. Examples of invalid string values include: Hello, world! "I said, "How are you?"" The first example is invalid as it is not within either single or double quotes. The second example is tricky. You will have problems assigning that value to a string because once PHP reads the second quotation mark, it assumes that the string ends there and the continuing text will cause an error. Then how do you use a quotation mark within a string you may wonder ? Just as discussed in Chapter 1 when using the print() function to create HTML, you can escape the quotation mark by putting a backslash (\) before it. By changing this string to "I said, \"How are you?\"", you have told PHP to include those two quotation marks as part of the value of the string, and not treat them as the string opening or closing indicators. So while any combination of characters can be included in a string, special characters must be escaped to print correctly. Along with the double quotation mark, you should also escape the apostrophe or single quotation mark ('), the backslash(\), and the dollar sign ($). Tip The benefit of using double quotes over single quotes with strings is that a variable's value will be printed out using the former but not the latter. If you use single quotes, the line print 'Hello, $FirstName!'; will result in Hello, $FirstName! being printed instead of, say, Hello, Larry! ( assuming $FirstName has been assigned the value of Larry ). If you escape the dollar sign within double quotes ( print "Hello, \$FirstName!"; ) you will once again print the name of the variable and not it's value (here, Hello, $FirstName! ). Tip In Chapter 1, Getting Started with PHP, I demonstrated how to create a new line by printing the \n character. Although escaping a quotation mark prints the quotation mark, escaping an "n" prints a new line, escaping an "r" creates a carriage return, and escaping a "t" inserts a tab into your code. |
I l @ ve RuBoard |