Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

The PHP Language 659

24


In this case, I have an associative array that has two elements. The values for each of the
elements are arrays themselves. I can access this data structure by stacking the references
to the array indexes, like this:


$colors = $stuff['colors']; // Returns the list of colors.
$color = $stuff['colors'][1]; // Returns 'green'
$number = $stuff['numbers'][0]; // Returns 'one'


Strings


The most common data type you’ll work with in PHP is the string type. A string is just a
series of characters. An entire web page is a string, as is a single letter. To define a string,
just place the characters in the string within quotation marks. Here are some examples of
strings:


"one"
"1"
"I like publishing Web pages."
"This string
spans multiple lines."


Take a look at the last string in the list. The opening quotation mark is on the first line,
and the closing quotation mark is on the second line. In PHP, this is completely valid. In
some programming languages, strings that span multiple lines are illegal—not so in PHP,
where strings can span as many lines as you like, so long as you don’t accidentally close
the quotation marks.


There’s more to strings than just defining them. You can use the. operator to join
strings, like this:


$html_paragraph = "

". $paragraph. "

";


The $html_paragraph variable will contain the contents of $paragraph surrounded by
the opening and closing paragraph tag. The. operator is generally referred to as the
string concatenation operator.


Up to this point, you might have noticed that sometimes I’ve enclosed strings in double
quotation marks, and that other times I’ve used single quotation marks. They both work
for defining strings, but there’s a difference between the two. When you use double quo-
tation marks, PHP scans the contents of the string for variable substitutions and for spe-
cial characters. When you use single quotation marks, PHP just uses whatever is in the
string without checking to see whether it needs to process the contents.


Special characters are introduced with a backslash, and they are a substitute for characters
that might otherwise be hard to include in a string. For example, \n is the substitute for a

Free download pdf