PHP Strings Primer - Double Quotes
(Page 4 of 37 )
Using double quotes gives us the ability to parse variables within our strings. To demonstrate this, let's look at a simple illustration:
<?php $var = 'Hello'; $mystring = "$var world"; ?> |
After these two lines of code execute, '$mystring' will contain the string 'Hello world'. So, as you can see, within double quotes variables are seen as variables and variable substitution occurs. This simple variable parsing doesn't work in all situations however. If, for instance, you wanted to use a value stored in an array rather than just the simple variable we have above, you would need to use what is called complex syntax. Complex syntax allows you to use objects and arrays in strings. A syntax error will occur if an object, or an array that utilizes an associative index, is included in a string without using complex syntax. To avoid the syntax error, we should make use of complex syntax by encapsulating the object or array in curly braces. The following example will demonstrate this syntax.
<?php $mystring = "This is an array value: {$myarray['foo']}."; ?> |
As with single quotes, we can place our string on multiple lines to place newlines in them. But, we also have another method available to us. By using the special sequence of '\n' we can also place a newline in a string.
<?php $mystring = "This is the first line,\n and this is the second line"; ?> |
We can also place horizontal tabs in our strings by using '\t'. If we want to include a double quote in the string, we can use the same method we explored with single quotes of escaping the double quote with a backslash character. In both the single and double quote methods, we should also escape the backslash character if we want it displayed. Let's take a look at an example with these other escape sequences.
<?php $mystring = "\tThis should be tabbed over\nAnd here is a newline. Now, let's display a backslash \\."; ?> |
Below is a list which details each escape sequence.
\n -linefeed or newline (LF or 0x0A (10) in ASCII)\r -carriage return (CR or 0x0D (13) in ASCII)\t -horizontal tab (HT or 0x09 (9) in ASCII)\\ -backslash\$ -dollar sign\" -double-quote\[0-7]{1,3} -the sequence of characters matching the regular expression is a character in octal notation\x[0-9A-Fa-f]{1,2} -the sequence of characters matching the regular expression is a character in hexadecimal notation
Next: Heredoc >>
More Programming Basics Articles
More By Matt Wade