By Hugh E. Williams, David Lane
Book Price: $44.95 USD
£31.95 GBP
PDF Price: $35.99
Cover | Table of Contents | Colophon
if, if...else, and the
switch statements<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Hello, world</title>
</head>
<body bgcolor="#ffffff">
<h1>
<?php
print "Hello, world";
?>
</h1>
</body>
</html>
<?php print "Hello, world"; ?>
true or
false. There are two branching statements in PHP:
if, with the optional else
clause, and switch, usually with two or more
case clauses.if
statement conditionally controls
execution. The basic format of an if statement is
to test whether a condition is true and, if so, to
execute one or more statements.if statement executes the
print statement and outputs the string when the
conditional expression, $var is greater than 5, is
true:if ($var > 5)
print "The variable is greater than 5";
true, the statements within the braces are
executed. If the expression isn't
true, none of the statements are executed.
Consider an example in which three statements are executed if the
condition is true:if ($var > 5)
{
print "The variable is greater than 5.";
// So, now let's set it to 5
$var = 5;
print "In fact, now it is equal to 5.";
}
if statement executes only
the single, immediately following statement when the conditional
expression evaluates to true.if statement can have an optional
else
clause to execute a statement or block
of statements if the expression evaluates as
false. Consider an example:if ($var > 5)
print "Variable greater than 5";
else
print "Variable less than or equal to 5";
true.
There are four loop statements in PHP: while,
do...while, for, and
foreach. The first three are general-purpose loop
constructs, while the foreach is used exclusively with arrays and is
discussed in the next chapter.while loop is the simplest looping structure
but sometimes the least compact to use. The while
loop repeats one or more statements—the loop body—as long
as a condition remains true. The condition is
checked first, then the loop body is executed. So, the loop never
executes if the condition isn't initially
true. Just as with the if
statement, more than one statement can be placed in braces to form
the loop body.while
statement by printing out the integers from 1 to 10 separated by a
space character:$counter = 1;
while ($counter < 11)
{
print $counter . " ";
$counter++;
}
while and
do...while is the point at which the condition is
checked. In do...while, the condition is checked
after the loop body is executed. As long as the
condition remains true, the loop body is repeated.while example as follows:$counter = 1;
do
{
print $counter . " ";
$counter++;
} while ($counter < 11);
while and
do...while can be seen in the following example:$counter = 100;
do
{
print $counter . " ";
$counter++;
} while ($counter < 11);
false.do...while loop is the least frequently used
loop construct, probably because executing a loop body once when a
condition is false is an unusual requirement.for loop is the most complicated of the loop
constructs, but it also leads to the most compact code.$var = "A string"; print strtoupper($var); // prints "A STRING"
$var = 42; print strtoupper($var); // prints the string "42"
$year = 2003; // Sets $yearString to the string value "2003" $yearString = strval($year); $var = "abc"; // sets $value to the integer 0 $value = intval($var); // sets $count to the integer value 2748 - the // integer value of "abc" as a hexadecimal number $count = intval($var, 16);
abc" doesn't
look anything like an integer, the first call to the
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Function Call</title>
</head>
<body bgcolor="#ffffff">
<?php
function bold($string)
{
print "<b>" . $string . "</b>";
}
// First example function call (with a static string)
print "this is not bold ";
bold("this is bold ");
print "this is again not bold ";
// Second example function call (with a variable)
$myString = "this is bold";
bold($myString);
?>
</body></html>
$string, and prints that
string prefixed by a bold <b> tag and
suffixed with a </b> tag. The parameter
$string is a variable that is available in the
body of the function, and the value of $string is
set when the function is called. As shown in the example, the
function can be called with a string literal expression or a variable
as the parameter.return statement:function heading($text, $headingLevel)
{
switch ($headingLevel)
{
case 1:
$result = "<h1>$text</h1>";
break;
case 2:
$result = "<h2>$text</h2>";
break;
case 3:
$result = "<h3>$text</h3>";
break;
default:
$result = "<p><b>$text</b></p>";
}
return($result);
}
$test = "User-defined Functions";
print heading($test, 2);
<head>
components and the <h1>The Times
Tables</h1> heading at the top of the web page.
Similarly, the last two lines are HTML that finishes the document:
</body> and
</html>.<?php and finishes with the close tag
?>.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>The Times-Tables</title>
</head>
<body bgcolor="#ffffff">
<h1>The Times Tables</h1>
<?php
// Go through each table
for($table=1; $table<13; $table++)
{
print "<p><b>The " . $table . " Times Table</b>\n";
// Produce 12 lines for each table
for($counter=1; $counter<13; $counter++)
{
$answer = $table * $counter;
// Is this an even-number counter?
if ($counter % 2 == 0)
// Yes, so print this line in bold
print "<br><b>$counter x $table = " .
"$answer</b>";
else
// No, so print this in normal face
print "<br>$counter x $table = $answer";
}
}
?>
</body>
</html>$numbers = array(5, 4, 3, 2, 1);
$words = array("Web", "Database", "Applications");
// Print the third element from the array of integers: 3
print $numbers[2];
// Print the first element from the array of strings: "Web"
print $words[0];
print strlen("This is a String"); // prints 16
echo and print.
Earlier in this chapter, we showed you the functions
print_r( ) and var_dump( ),
which can determine the contents of variables during debugging. PHP
provides several other functions that allow more complex and
controlled formatting of strings, and we discuss them in this
section.echo or print. For example, a
floating-point value such as 3.14159 might need to be truncated to
3.14 in the output. For complex formatting, the sprintf(
)
or printf( )
functions are useful:true if the
regular expression pattern is found in the
subject string. We discuss how the
ereg( ) function can extract values into the
optional array variable var later in this
section.cat in the
subject string "raining cats and dogs":// prints "Found 'cat'"
if (ereg("cat", "raining cats and dogs"))
print "Found 'cat'";
cat matches the
subject string, and the fragment prints
"// prints the current timestamp: e.g., 1064699133 print time( );
// Largest positive integer (for a 32 bit signed integer) $variable = 2147483647; // prints int(2147483647) var_dump($variable); $variable++; // prints float(2147483648) var_dump($variable);
$var = 42; // a positive integer $var = -186; // a negative integer $var = 0654; // 428 expressed as an octal number $var = 0xf7; // 247 expressed as a hexadecimal number
$var = 42.0; // a positive float $var = -186.123; // a negative float $var = 1.2e65; // a very big number $var = 10e-75; // a very small number
+,
-, /, *, and
%, PHP provides the usual array of mathematical
library functions. In this section, we present some of the library
functions that are used with integer and float numbers.print abs(-1); // prints 1 print abs(1); // prints 1 print abs(-145.89); // prints 145.89 print abs(145.89); // prints 145.89
$template. All the complex implementation of
templates is hidden: you just load in the proper package and issue a
PHP statement such as:$template = new HTML_Template_IT("./templates");
$template and is
built by the HTML_Template_IT package—a
package whose code you don't need to know anything
about. Once you have a template object, you can access the
functionality provided by the HTML_Template_IT
package.$template
object, you can insert the results into your web page through the PHP
statement:$template->show( );
$template. All the complex implementation of
templates is hidden: you just load in the proper package and issue a
PHP statement such as:$template = new HTML_Template_IT("./templates");
$template and is
built by the HTML_Template_IT package—a
package whose code you don't need to know anything
about. Once you have a template object, you can access the
functionality provided by the HTML_Template_IT
package.$template
object, you can insert the results into your web page through the PHP
statement:$template->show( );
-> operator associates show(
) with the object variable $template.
When the function show( ) is called, it uses the
data that is held by the $template object to
calculate a result: put another way, show( ) is
called on the $template
object.$template. In traditional object-oriented
parlance, show( ) is called a
method
or member
function
of the
HTML_Template_IT object.new statement you are said to
create an instance of the class. Thus, the
$template object is an instance of the
extends keyword.<?php
// Access to the UnitCounter class definition
require "example.4-1.php";
class CaseCounter extends UnitCounter
{
var $unitsPerCase;
function addCase( )
{
$this->add($this->unitsPerCase);
}
function caseCount( )
{
return ceil($this->units/$this->unitsPerCase);
}
function CaseCounter($caseCapacity)
{
$this->unitsPerCase = $caseCapacity;
}
}
?>
throw
and
try...catch
statements.throw and try...catch
statements provide a way of jumping to error handling code in
exceptional circumstances: rather than terminating a script with a
fatal error, exceptions are thrown, and can be
caught and processed. The
throw statement is always used in conjunction with
the try...catch statement, and the following
fragment shows the basic structure:$total = 100;
$n = 5;
$result;
try
{
// Check the value of $n before we use it
if ($n == 0)
throw new Exception("Can't set n to zero.");
// Calculate an average
$result = $total / $n;
}
catch (Exception $x)
{
print "There was an error: {$x->getMessage( )};
}
try keyword are executed normally as part of the
script; the braces are required, even for a single statement. If a
throw statement is called in the
try block, then the statements contained in the
braces that follow the catch keyword are executed.
The throw
statement throws
an object and the catch block of code
catches the thrown object, assigning it to the
variable specified.$x:catch (Exception $x)
{
print "There was an error: {$x->getMessage( )};
}
catch block is an example of a class
type hint
. We discuss class type
hints in Chapter 14.