Using
if
Statements
Here's where you can start making choices based
on your data: by using
if
statements. Just about all
high-level programming languages, including PHP, have an
if
statement, and here's what it looks like
formally
:
if (
expression
)
statement
Here,
expression
is an expression that can be
evaluated to a boolean
trUE
/
FALSE
value. For
example, if
expression
were
5
> 2
, then it would evaluate to
TRUE
because
5
is greater than
2
. If
expression
is
TRUE
, then
statement
is executed; if
expression
is
FALSE
,
statement
is not executed.
The
if
statement is great because your
script can make choices at run time, based on the run-time value of
your data, which can include text the
user
has entered in a web
page (such as a password), values retrieved from a database (such
as inventory available), or even data
fetched
from another web site
(such as stock prices).
Here's an example that tests whether the value
in a variable named
$temperature
is less than 80
degrees:
<?php
$temperature = 75;
if ($temperature < 80)
echo "Nice day.";
?>
In this case,
$temperature
holds a
value of
75
, so the statement
echo "Nice day.";
is executed, and this is what you see:
Nice day.
But what if you have multiple statements you
want to execute if a certain condition is true? That's no problema
PHP statement can also be a
compound
statement
, which means it can contain any number of simple
statements, as long as you enclose them in curly braces.
For example, here are three simple statements
made into one compound PHP statement just by enclosing them between
{
and
}
:
{
echo "Your time is up!<BR>";
echo "Please put the phone down.";
$hang_up_now = TRUE;
}
You can see how this new compound statement
might appear inside an
if
statement in phpif.php, Example
2-5.
Example 2-5. Using the
if
statement, phpif.php
<HTML>
<HEAD>
<TITLE>Using the if statement</TITLE>
</HEAD>
<BODY>
<H1>Using the if statement</H1>
<?php
$minutes= 4;
if($minutes > 3) {
echo "Your time is up!<BR>";
echo "Please put the phone down.";
$hang_up_now = TRUE;
}
?>
</BODY>
</HTML>
And you can see this new example at work in
Figure 2-6.
Here's another example. PHP has functions named
is_int
,
is_float
,
is_array
, and so on to
return the type of a variable. Using them, you can test the type of
a variable before using it, like this:
if (is_int($variable))
$variable = $variable + 10;
The
if
statement is a basic one that
you'll use in practically all your scriptsand more on it is coming
up in this chapter.
|