<<

. 20
( 132 .)



>>

{
echo “˜$a™ is not FALSE\n”;
}



The result:

˜0™ is 0
˜0™ is not FALSE

This kind of flexibility is nice, but it can lead to some difficulty. There will be
times when you™re not sure what variable types you are working with. We™ll show
you how to deal with these circumstances in the section “Testing Variables” later in
this chapter.
94 Part II: Working with PHP


Delimiting strings
In the preceding code, all the strings were surrounded by double quotes. You can
also delimit strings in PHP in two other ways. If you surround your strings with
double quotes, variables within the string will be expanded. For instance,

$my_name = “Jay”;
$phrase = “Hello, my name is $my_name”;
echo $phrase;

will print “Hello, my name is Jay”. But if you want to include any of the follow-
ing characters within your string, they must be escaped with backslashes:

— Double quotes (“)

— Backslash (\)

— Dollar sign ($)

For example, to print an opening form tag using double quotes you would have
to do the following:

echo “<form action=\”mypage.php\” method=\”get\”>”;

You can also surround strings with single quotes (˜). If a string is within single
quotes, variables will not be expanded. So this code ”

$my_name = “Jay”;
echo ˜Hello, my name is $my_name™;

” will print “Hello, my name is $my_name”. The only characters that need to be
escaped within single quotes are single quotes and backslashes.
The flip side of this is that variable references will not be expanded inside single
quotes. If we repeat the first example in this section with single quotes:

$my_name = ˜Jay™;
$phrase = ˜Hello, my name is $my_name™;
echo $phrase;

PHP prints out “Hello, my name is $my_name”.
Since PHP knows that it does not have to parse a single-quoted string for vari-
able references, it™s marginally faster to use single-quotes to delimit constant val-
ues in your code. In recent releases, however, the performance difference between
the two styles has shrunk to insignificance. So it™s a matter of your personal prefer-
ence, and of which style is most convenient for what you™re trying to do.
Chapter 4: Getting Started with PHP ” Variables 95

Finally, you can also make use of heredoc syntax to delimit strings. The heredoc
syntax can be thought of as a hybrid of the single- and double-quote styles that
can be convenient in many circumstances. Heredoc text is delimited at the start of
the string with three less-than signs (<<<) and an identifier. An identifier must con-
tain only numbers, letters, and underscores and begin with either a letter or an
underscore; in the book we use the identifiers EOQ and EOT. The text is terminated
with the same identifier followed by a semicolon (;), on the left margin of the code.
This is important to remember ” heredoc terminators must not be indented, and the
terminator and semicolon must be the only characters on the line, with no spaces
before or after the semicolon. In the following code, $my_string is a string prop-
erly delimited using heredoc syntax.

$my_string = <<<EOQ
My string is in here.
EOQ;

If you use heredoc syntax, variables are expanded and double quotes do not
need to be escaped. We make frequent use of the heredoc syntax when working
with form elements, as is the case here:

$element = <<<EOQ
<textarea name=”$name” cols=”$cols” rows=”$rows”
wrap=”$wrap”>$value</textarea>
EOQ;

In a case like this we don™t need to litter the string with backslashes, and we still
get the convenience of having variables expanded within the string.
Note that when using heredoc syntax your file format should match the operat-
ing system it runs on. PHP is expecting a newline character as defined by the oper-
ating system to be the last character before the beginning of the heredoc terminator,
and for the terminator and a semicolon to be the only characters on their line. It
will produce an error if it is not. Unix-based operating systems (which includes Mac
OS X) use a newline character (\n) to terminate lines, while classic Mac (OS 9 and
earlier) files use a carriage return (\r), and DOS and Windows files use both (\n\r).
Editing your files on one operating system and running them on a different one can
cause difficult-to-diagnose errors. Most text editors enable you to save as a Unix
file type, and if you are running your scripts on a Unix server, choosing that option
saves you a lot of trouble.


If you want to reference an element in an associative array, an object prop-
erty, or make any other kind of variable reference that could be interpreted
ambiguously, you should enclose the variable in curly braces, like so:
$array = array (“fname”=>”jay”, “lname”=>”greenspan”);
$fields = <<<EOQ
96 Part II: Working with PHP

The value in array of ˜fname™ is {$array[˜fname™]}
EOQ;
foreach ($array as $key => $value)
{
$fields .= <<<EOQ
[˜™]<input type=”text” name=”{$key}_value”
value=”$value”>
EOQ;
}




Assigning arrays within a script
Arrays are variables that contain multiple values. For example, a simple array might
store the months of the year. To assign this array, you could use the following:

$months = array(“January”, “February”, “March”, “May”, “June”,
“July”, “August”, “September”, “October”, “November”, “December”);

This array has 12 elements, and you can address them by their order in the array,
starting with 0. So the command echo $months[0] would print “January” and
echo $months[11] would print “December”. To print out all the values within an
array, you could get the length of the array and then set up a loop, as follows:

$months = array(“January”, “February”, “March”, “May”, “June”,
“July”, “August”, “September”, “October”, “November”, “December”);
for ($i=0, $mcount=count($months); $i<$mcount; $i++)
{
echo $months[$i] . “<br>\n” ;
}



The for loop is explained in Chapter 5.




You can also assign values to arrays with a simple assignment operator. The fol-
lowing would work:

$dogs = array();
$dogs[0] = “shepherd”;
$dogs[1] = “poodle”;
Chapter 4: Getting Started with PHP ” Variables 97

If you don™t specify an index value, the value will be tacked onto the end of the
array. The following line would assign “retriever” to $dogs[2].

$dogs[] = “retriever”;



A variety of functions work with arrays. Many of these are covered in
Chapter 6.




Like many programming languages, PHP makes use of associative arrays. If you
are new to the concept, elements in associative arrays have keys that reference indi-
vidual elements. (In fact, all array values have keys. The difference with an associa-
tive array is that the keys are meaningful and can be strings as well as integers,
whereas in a simple list array, they represent only the position of the value in the
array.) Keys are particularly important when you™re dealing with databases. When
you fetch rows from your database query you will usually refer to the elements by
their keys.
You can assign an associative array by using keys. Here, first_name,
last_name, and email are the keys:

$person = array (
“first_name” => “Jay”,
“last_name” => “Greenspan”,
“email” => “jgreen_1@yahoo.com”
);

If you wanted to add to this array, you could assign another value. Notice that
the next line would add an integer to the array, so this array would then contain
four values - three strings and one integer:

$person[˜age™] = 32;

Typically, if you wanted to access both the keys and the values in an associative
array, you would use the list()=each() construct or the foreach() loop. Here are
some examples:

while (list($key, $value) = each($person))
{
echo “<b>key:</b> $key, <b>value</b> = $value <br>\n”;
}
98 Part II: Working with PHP

Chapter 5 describes the list()=each() construct in more detail. Basically,
each() pulls the key and value of a single array element; list() takes those val-
ues and assigns them to $key and $value, respectively. This process continues until
each element in the array has been accessed. If you want to go through the array a
second time, you will need to reset the array pointer with reset($person).
If you wanted to get only the value without the key, or if you were using a non-
associative array and wanted to use the list()=each() structure, you would have
to do this:

while (list( , $value) = each($person))
{
echo “value = $value <br>\n”;
}

Or, if you wanted to get at just the keys, you could do this:

while (list($key) = each($person))
{
echo “key = $key <br>\n”;
}

You can also cycle through arrays using the foreach() loop. The following will
print out the keys and values for each element of the $person array:

foreach($person as $key=>$value)
{
echo “key = $key; value = $value <br>\n”;
}

And the following will print out just the values of array elements:

foreach($person as $value)
{
echo “value = $value <br>\n”;
}

With foreach() there™s no need to reset the array pointer after looping through
the array. It is also appreciably faster than the list()=each() syntax.


Think about PHP arrays this way: All arrays are associative. A couple of pages
back you saw that you can assign a basic array without specifying associa-
tive keys. For example, $myarray= array (“pug”, “poodle”). When
this is done, PHP assigns $myarray consecutive numeric keys starting at 0.
Chapter 4: Getting Started with PHP ” Variables 99

They behave just like associative keys. You step through them using
list()=each() or foreach(). They make use of the same array func-
tions, many of which are explained in Chapter 6.



Assigning two-dimensional arrays in a script
PHP also supports multidimensional arrays. The most commonly used multidimen-
sional array is the two-dimensional array. Two-dimensional arrays look a lot like
tables. They store information that is based on two keys. For instance, if you
wanted to store information on more than one person, a two-dimensional array
would work well. You would assign an array named $people, which would contain
individual arrays addressing each person:

$people = array (
“jay” => array (
“last_name” => “greenspan”,
“age” => 32
),
“john” => array (

<<

. 20
( 132 .)



>>