By David Sklar
Book Price: $29.95 USD
£20.95 GBP
PDF Price: $23.99
Cover | Table of Contents | Colophon
www.example.com asking for the
/catalog.html page.www.example.com computer, gets the message and reads the
www.example.com asking for the
/catalog.html page.www.example.com computer, gets the message and reads the
catalog.html file from the disk drive.http://www.php.net/. Appendix A has detailed instructions on how to
install PHP.<?php (the PHP start tag) and ?> (the PHP end tag). PHP pages typically live in files
whose names end in .php. Example 1-1 shows a page with one PHP command.<html> <head><title>PHP says hello</title></head> <body> <b> <?php print "Hello, World!"; ?> </b> </body> </html>
<html> <head><title>PHP says hello</title></head> <body> <b> Hello, World! </b> </body> </html>
<?php as the PHP start tag and ?> as the PHP end tag. The PHP interpreter ignores anything outside of
those tags. Text before the start tag or after the end tag is printed with no
interference from the PHP interpreter.Five plus five is: <?php print 5 + 5; ?> <p> Four plus four is: <?php print 4 + 4; ?> <p> <img src="vacation.jpg" alt="My Vacation">
<?php
?> tags is processed by the PHP interpreter,
and the rest of the page is printed as is. Example 1-8 prints:Five plus five is: 10<p> Four plus four is: 8<p> <img src="vacation.jpg" alt="My Vacation">
<?php and ?>), whitespace, case-sensitivity, and comments.I would like 1
bowl of soupI would like 1
bowl of soup, and "Is it too hot?" he
asked, and There's
no spoon!. A string can even contain the contents of
a binary file such as an image or a sound. The only limit to the length of a string in a
PHP program is the amount of memory your computer has.print 'I would like a bowl of soup.'; print 'chicken'; print '06520'; print '"I am eating dinner," he growled.';
I would like a bowl of soup.chicken06520"I am eating dinner," he growled.
print statements
appears all on one line. No linebreaks are added by print.\)
before the single quote inside the string:print 'We\'ll each have a bowl of soup.';
\' sequence is turned into ' inside the
string, so what is printed is:We'll each have a bowl of soup.
print 56; print 56.3; print 56.30; print 0.774422; print 16777.216; print 0; print -213; print 1298317; print -9912111; print -12.52222; print 0.00;
$ followed by the variable's
name. To assign a value to a variable, use an
equals sign (=).
This is known as the assignment operator.$plates = 5; $dinner = 'Beef Chow-Fun'; $cost_of_dinner = 8.95; $cost_of_lunch = $cost_of_dinner;
$page_header = <<<HTML_HEADER <html> <head><title>Menu</title></head> <body bgcolor="#fffed9"> <h1>Dinner</h1> HTML_HEADER; $page_footer = <<<HTML_FOOTER </body> </html> HTML_FOOTER;
|
Acceptable
|
|---|
$size
|
$drinkSize
|
$my_drink_size
|
$_drinks
|
$drink4you2
|
printf( ).strtolower(
), strtoupper( ), or ucwords( ).substr(
).str_replace(
).<? php print 'How are you?'; print 'I'm fine.'; ??>
$first_name to your first name and $last_name to your last name. Print out a string containing your first
and last name separated by a space. Also print out the length of that
string.++) and the combined multiplication operator (*=) to print out the numbers from 1 to 5 and powers
of 2 from 2 (21) to 32
(25).true or false. Section 3.1 explains how the interpreter decides
which expressions and values are true and which are
false.true and false values are used by language constructs such as if( ) to decide whether to run certain statements in a program. The ins and
outs of if( ) are detailed later in this chapter in
Section 3.2. Use if( ) and similar constructs any time the outcome of a program depends on
some changing conditions.true and false are the cornerstones of decision making, usually you want to ask more
complicated questions, such as "is this user at least 21 years old?" or "does this user
have a monthly subscription to the web site or enough money in their account to buy a daily
pass?" Section 3.3, later in this chapter,
explains PHP's comparison and logical operators. These help you express whatever kind of
decision you need to make in a program, such as seeing whether numbers or strings are
greater than or less than each other. You can also chain together decisions into a larger
decision that depends on its pieces.true or false. Sometimes that truth value
is important because you use it in a calculation, but sometimes you ignore it.
Understanding how expressions evaluate to
true or to false
is an important part of understanding PHP.true. All integers and
floating-point numbers (except for 0 and 0.0) are true. All strings are true except for two: a string containing nothing at all and a string
containing only the character 0. These four values
are false. The special constant false also evaluates to false. Everything else is true.false values, or a function that
returns one of those values also evaluates to false.
Every other expression evaluates to true.true or false. Some
expressions have common sense values. The value of a mathematical expression is what
you'd get by doing the math with paper and pencil. For example, 7 * 6 equals 42. Since 42 is true, the expression 7 *
6 is true. The expression 5 - 6 + 1 equals 0.
Since 0 is false,
the expression 5 - 6 + 1 is false.jacob' . '@example.com' equals the string
jacob@example.com, which is true.$price
=
5 evaluates to 5,
since that's what's being assigned to $price. Because
assignment produces a result, you can chain assignment operations together to assign the
same value to multiple variables:if( ) construct, you can have statements in your
program that are only run if certain conditions are true. This lets your program take different actions depending on the
circumstances. For example, you can check that a user has entered valid information in a
web form before letting her see sensitive data.if( ) construct runs a block of code if its
test expression is true. This is demonstrated in
Example 3-1.if ($logged_in) {
print "Welcome aboard, trusted user.";
}
if( ) construct finds the truth value of the
expression inside its parentheses (the test expression). If the
expression evaluates to true, then the statements inside the curly braces after the if( )
are run. If the expression isn't true, then the
program continues with the statements after the curly braces. In this case, the test
expression is just the variable $logged_in. If
$logged_in is true (or has a value such as 5, -12.6, or Grass Carp,
that evaluates to true), then Welcome aboard, trusted user. is printed.if( ) statement.
You don't, however, need a semicolon after the closing curly brace that encloses the
code block. You also don't put a semicolon after the opening curly brace. Example 3-2 shows an if( ) clause that runs multiple statements when its test expression is
true.print "This is always printed.";
if ($logged_in) {
print "Welcome aboard, trusted user.";
print 'This is only printed if $logged_in is true.';
}
print "This is also always printed.";if( )
construct can
decide. These operators let you compare values, negate values, and chain together
multiple expressions inside one if( ) statement.= =. It returns true
if the
two values you test with it are equal. The values can be variables or literals. Some
uses of the equality operator are shown in Example
3-6.if ($new_messages == 10) {
print "You have ten new messages.";
}
if ($new_messages == $max_messages) {
print "You have the maximum number of messages.";
}
if ($dinner == 'Braised Scallops') {
print "Yum! I love seafood.";
}
!=. It returns true if the two values that
you test with it are not equal. See Example
3-7.<select> menu. The two looping constructs discussed in
this section are while( ) and for( ). Their specifics differ but they each require you to
specify the two essential attributes of any loop: what code to execute repeatedly and
when to stop. The code to execute is a code block just like what goes inside the curly
braces after an if( ) construct. The condition for
stopping the loop is a logical expression just like an if(
) construct's test expression.while( )
construct is
like a repeating if( ). You provide an expression to
while( ), just like to if( ). If the expression is true, then a code
block is executed. Unlike if( ), however, while( ) checks the expression again after executing the
code block. If it's still true, then the code block
is executed again (and again, and again, as long as the expression is true.) Once the expression is false, program execution continues with the lines after the code block. As
you have probably guessed, your code block should do something that changes the outcome
of the test expression so that the loop doesn't go on forever.while( ) to print out an HTML form
<select> menu with 10 choices.$i = 1;
print '<select name="people">';
while ($i <= 10) {
print "<option>$i</option>\n";
$i++;
}
print '</select>';
<select name="people"><option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> </select>
true
or false.if( ).if( ) with else.if( ) with elseif( ).if( ),
elseif( ), or else code block.= =) and not-equals
(!=) operators in test expressions.=) and
equality comparison (= =).<), greater-than
(>), less-than-or-equal-to (<=), and greater-than-or-equal-to (>=) operators in test expressions.abs(
).strcmp( ) or
strcasecmp( ).!) in test
expressions.&& and
||) to build more complicated test
expressions.while( ).for( ).true or
false:100.00 - 100
zero"false"0 + "true"0.000
0.0"strcmp("false","False")
$age = 12;
$shoe_size = 13;
if ($age > $shoe_size) {
print "Message 1.";
} elseif (($shoe_size++) && ($age > 20)) {
print "Message 2.";
} else {
print "Message 3.";
}
print "Age: $age. Shoe Size: $shoe_size";
while( ) to print out a table of
Fahrenheit and Celsius temperature equivalents from -50 degrees F to 50 degrees F
in 5-degree increments. On the Fahrenheit temperature scale, water freezes at 32
degrees and boils at 212 degrees. On the Celsius scale, water freezes at 0 degrees
and boils at 100 degrees. So, to convert from Fahrenheit to Celsius, you subtract
32 from the temperature, multiply by 5, and divide by 9. To convert from Celsius
to Fahrenheit, you multiply by 9, divide by 5, and then add 32.for(
) instead of while( ).foreach( ) and for(
) constructs. Section 4.3
introduces the implode( ) and explode( ) functions, which turn arrays into strings and strings into arrays.
Another kind of array modification is sorting, which is discussed in Section 4.4. Last, Section 4.5 explores arrays that themselves
contain other arrays.
corn even
if its value is blue. However, the same value can
appear many times in one array. You can have orange carrots, orange tangerines, and
orange oranges.
corn even
if its value is blue. However, the same value can
appear many times in one array. You can have orange carrots, orange tangerines, and
orange oranges.corn, 4, -36, or Salt
Baked
Squid. Arrays and other nonscalar values can't be keys, but they can be element values. An element value can
be a string, a number, true, or false; it can also be another array.// An array called $vegetables with string keys $vegetables['corn'] = 'yellow'; $vegetables['beet'] = 'red'; $vegetables['carrot'] = 'orange'; // An array called $dinner with numeric keys $dinner[0] = 'Sweet Corn and Asparagus'; $dinner[1] = 'Lemon Chicken'; $dinner[2] = 'Braised Bamboo Fungus'; // An array called $computers with numeric and string keys $computers['trs-80'] = 'Radio Shack'; $computers[2600] = 'Atari'; $computers['Adam'] = 'Coleco';
corn, Braised Bamboo
Fungus, and Coleco) and numbers (such as 0,
1, and 2600). They are written just like other strings and numbers in PHP
programs: with quotes around the strings but not around the numbers.foreach( )
. The foreach( )
construct lets you run a code block once for each element in an array. Example 4-7 uses foreach( ) to print an HTML table containing each element in an array.$meal = array('breakfast' => 'Walnut Bun',
'lunch' => 'Cashew Nuts and White Mushrooms',
'snack' => 'Dried Mulberries',
'dinner' => 'Eggplant with Chili Sauce');
print "<table>\n";
foreach ($meal as $key => $value) {
print "<tr><td>$key</td><td>$value</td></tr>\n";
}
print '</table>';
<table> <tr><td>breakfast</td><td>Walnut Bun</td></tr> <tr><td>lunch</td><td>Cashew Nuts and White Mushrooms</td></tr> <tr><td>snack</td><td>Dried Mulberries</td></tr> <tr><td>dinner</td><td>Eggplant with Chili Sauce</td></tr> </table>
$meal, foreach( ) copies the key of the element into $key and the value into $value. Then, it runs the code inside the curly braces. In Example 4-7, that code prints $key and $value with
some HTML to make a table row. You can use whatever variable names you want for the key
and value inside the code block. If the variable names were in use before the foreach( ), though, they're overwritten with values from
the array.foreach( ) to print out data in
an HTML table, often you want to apply alternating colors or styles to each table row.
This is easy to do when you store the alternating color values in a separate array.
Then, switch a variable between 0 and 1 each time through the foreach(
)$dishes['Beef Chow Foon'] = 12;
$dishes['Beef Chow Foon']++;
$dishes['Roast Duck'] = 3;
$dishes['total'] = $dishes['Beef Chow Foon'] + $dishes['Roast Duck'];
if ($dishes['total']> 15) {
print "You ate a lot: ";
}
print 'You ate ' . $dishes['Beef Chow Foon'] . ' dishes of Beef Chow Foon.';
You ate a lot: You ate 13 dishes of Beef Chow Foon.
$meals['breakfast'] = 'Walnut Bun'; $meals['lunch'] = 'Eggplant with Chili Sauce'; $amounts = array(3, 6); print "For breakfast, I'd like $meals[breakfast] and for lunch, "; print "I'd like $meals[lunch]. I want $amounts[0] at breakfast and "; print "$amounts[1] at lunch.";
For breakfast, I'd like Walnut Bun and for lunch, I'd like Eggplant with Chili Sauce. I want 3 at breakfast and 6 at lunch.
sort( )
function sorts an array by its element values. It should only
be used on numeric arrays, because it resets the keys of the array when it sorts. Example 4-23 shows some arrays before and
after sorting.$dinner = array('Sweet Corn and Asparagus',
'Lemon Chicken',
'Bra