65
44
Chapter 1 PHP Crash Course
Refresh the page to see the results.
The variable
$tireqty
should return 1 (
true
) from
isset()
regardless of what value
you entered in that form field and regardless of whether you entered a value at all.
Whether it is
empty()
depends on what you entered in it.
The variable
$nothere
does not exist,so it generates a blank (
false
) result from
isset()
and a 1 (
true)
result from
empty()
.
These functions can be handy when you need to make sure that the user filled out
the appropriate fields in the form.
Reinterpreting Variables
You can achieve the equivalent of casting a variable by calling a function.The following
three functions can be useful for this task:
int intval(mixed var[, int base]);
float floatval(mixed var);
string strval(mixed var);
Each accepts a variable as input and returns the variable’s value converted to the appro-
priate type.The
intval()
function also allows you to specify the base for conversion
when the variable to be converted is a string. (This way,you can convert, for example,
hexadecimal strings to integers.)
Implementing Control Structures
Control structures are the structures within a language that allow you to control the flow
of execution through a program or script.You can group them into conditionals (or
branching) structures and repetition structures (or loops).We consider the specific imple-
mentations of each of them in PHP next.
Making Decisions with Conditionals
If you want to sensibly respond to your users’ input, your code needs to be able to make
decisions.The constructs that tell your program to make decisions are called conditionals.
if Statements
You can use an
if
statement to make a decision.You should give the
if
statement a
condition to use.If the condition is
true
,the following block of code will be executed.
Conditions in
if
statements must be surrounded by parentheses
()
.
For example,if a visitor orders no tires, no bottles of oil,and no spark plugs from
Bob,it is probably because she accidentally clicked the Submit Order button before she
had finished filling out the form. Rather than telling the visitor “Order processed,”the
page could give her a more useful message.