<<

. 23
( 132 .)



>>

book on Unix systems running Apache Web servers. But, as PHP runs on a variety
of operating systems and Web servers and MySQL runs on Windows as well as
Unix, you should be aware of the different variables associated with whatever Web
server and operating system you™re running.
112 Part II: Working with PHP

You™ll see that the files imported into in our applications via include statements
make use of the DOCUMENT_ROOT Apache variable. If you were to attempt to move
the application files to a server other than Apache on Windows, you would get an
error in the include statements. The better choice when using Microsoft™s Personal
Web Server is the $APPL_PHYSICAL_PATH variable.



Testing Variables
At the start of this chapter, we showed that assigning data to a variable determines
the variable type. The appearance of the variable gives no indication as to what the
variable contains. If you see $var sitting in a script you™ll have no idea if it con-
tains a string, an integer, a floating-point number, or an array. In fact, many times
in your scripts you won™t be sure if the variable contains a value, or even if it exists
at all. For all these reasons, you need to perform tests. The following sections
describe the types of tests you can perform.

isset()
This function tests whether a variable has any value, including an empty string. It
returns a value of either TRUE or FALSE. If the variable has not been initialized or
has been set to NULL, isset() will return FALSE. In code snippets throughout this
chapter we showed the use of isset() to test whether the script was encountering
a submitted form.
If you wish to destroy a variable, use the unset() function.

empty()
The empty() function overlaps somewhat with the isset() function. It returns
TRUE if a variable is not set, is an array with no elements, or has a value of " " (an
empty string), 0, NULL, or FALSE. It is useful for, among other things, processing
form data. If you want to determine if the user has put something in a text field, for
example, you might try something like this:

if ($_POST[“first_name”] == “”)
{
echo “Please enter your first name. It is a required field”;
exit;
}

However, PHP complains that first_name is an undefined index value. That™s
because if you leave a text field on a form blank, nothing is submitted by the form
for that field. So no entry with the field™s name exists in $_POST. But the empty()
function enables you to check for things that aren™t there:
Chapter 4: Getting Started with PHP ” Variables 113

if (empty($_POST[˜first_name™]))
{
echo “Please enter your first name. It is a required field”;
exit;
}


is_null()
Starting in version 4.2, PHP supports the NULL variable type. Most often you will be
using NULL when examining data returned from a database.

is_int()
This function tests whether a variable is an integer. It has two synonyms: is_
integer() and is_long(). You may need this function to troubleshoot a script
when you™re not sure whether a variable is an integer or a string containing numerals.

$a = “222”;
$b = 22;

Given these two variable assignments, is_int($a) would test FALSE and
is_int($b) would test TRUE.


is_double()
This function tests whether a variable is a floating-point (or double) number. It has
two synonyms: is_float() and is_real().

is_string()
This function tests whether a variable is a text string.

is_array()
This function tests whether a variable is an array. It is used frequently in the course
of this book. A good example can be found in Chapter 6, in the discussion of the
implode() function.


is_bool()
This function tests whether a variable is Boolean (contains either TRUE or FALSE).
Note that the following examples are not Boolean:

$a = “TRUE”;
$b = “FALSE”;
114 Part II: Working with PHP

In Chapter 6 you will see a variety of functions that return FALSE on failure. In
these, FALSE is a Boolean value.

is_object()
Returns TRUE if the variable is an object. See Chapter 7 for a discussion of objects
and object-oriented programming if you don™t know what an object is.

is_resource()
Returns TRUE if the variable is a resource. An example of a resource variable is the
connection value returned by mysql_connect().

is_scalar()
Returns TRUE if the variable is of any type other than array, object, or resource.

gettype()
This function will tell you the type of variable you have. It will return the expected
values (string, double, integer, array, boolean, or resource), and it can also
return types related to object-oriented programming (object). You can find more
information on PHP object-oriented programming in Chapter 7.
Note that gettype() returns a string. So in the following example, the condi-
tional would test as true and print “Yes”:

$str = “I am a string”;
$type = gettype($str);
if ($type == “string”)
{
echo “Yes”;
}




Changing Variable Types
You can change the type of any variable in three ways.

Type casting
You can change the variable type by placing the name of the variable type you
require in parentheses before the variable name:

$a = 1;
$b = (string) $a;
Chapter 4: Getting Started with PHP ” Variables 115

echo gettype($a), “<br>\n”;
echo gettype($b), “<br>\n”;

This code would print

integer
string

Using this method you can cast a variable as an array, a double, an integer, or,
as in the preceding code, a string. Casting to type object is less reliable.

Using settype()
This function takes two arguments. The first is a variable name. The second speci-
fies the variable type. The advantage of using this function over casting is that
settype() will return a value of FALSE if the conversion fails, while there is no
way to detect a failed casting. This function can take the same types as listed in
type casting.

$a = 1;
settype($a, “string”);


intval(), doubleval(), and stringval()
Finally, if you don™t have enough ways to evaluate variable types, use one of these
functions. They do not actually change the type of the variable, but return a value
of the specified type. So in the following examples, you can be sure $a will be
treated like an integer:

$a = “43”;
$b = (intval($a) * 2);




Variable Variables
PHP includes variable variables, which, in the wrong hands, could be used to write
the most incomprehensible code imaginable. Variable variables enable you to take
the contents of a variable and use them as variable names. Two consecutive dollar
signs let PHP know to take the value of the variable and use it as a variable name.
The following creates a variable name $foo with a value of “bar”:

$a = ˜foo™;
$$a = ˜bar™;
116 Part II: Working with PHP

In the context of a database application, variable variables might be used to cre-
ate a series of variables against which you compare other variables. In the follow-
ing example, $firstrow is an associative array:

$firstrow = array (“firstname”=>”jay”, “lastname”=>”greenspan”);
foreach ($firstrow as $field => $value)
{
$field = “first_{$field}”;
$$field = $value;
}
echo $first_firstname, “ “, $first_lastname;

When your script runs through the foreach loop, the following variables would
be created and printed:

$first_firstname = “jay”
$first_lastname = “greenspan”




Summary
If you read this chapter attentively (or even if you didn™t) you should have a pretty
good idea of how to work with PHP variables.
PHP does a better job than any scripting language of making variables easy to
access and process. If you want to get a feel for how PHP variables are used, take a
look at Chapter 8, which contains the first application in the book. There, many of
the functions and concepts presented here are put to work. By flipping back and
forth between this chapter and those scripts, you will see how variables are used
and how scripts come together.
One very important point: This chapter did not discuss variable scope, which is
an important topic. See Chapter 7 where we discuss functions, for an explanation
of this topic.
Chapter 5

Control Structures
IN THIS CHAPTER

— Understanding the syntax of if statements

— Determining true and false values with PHP

— Learning PHP loops

— Choosing loops to use in your scripts



CONTROL the building blocks of programming languages. PHP has
STRUCTURES ARE
all the control structures needed to make a language work. If you™re familiar with C
or Perl, none of the features we discuss in this chapter should come as much of a
surprise. However, if you™re approaching PHP from a background in VBScript or
Visual Basic, the syntax will probably be different from what you™re used to. (If you
aren™t familiar with functions, you might want to peek ahead to the beginning of
the next chapter for a quick overview ” but come right back!) If you find the syn-
tax to be a little heavy at first, stick with it. You might find that the extra brackets
and parentheses actually help you write readable code.



The if Statement
The if statement is pretty much the cornerstone of all programming languages. In
PHP, an if statement typically takes this basic form:

if (condition or set of conditions)
{
actions to perform if condition is true.
}

After the word if is a set of parentheses. Within those parentheses is the single
condition or set of conditions to be tested. If the condition is evaluated as being
true, the code within the curly braces will execute. The following will test true and
print “I™m True!” to a Web page.


117
118 Part II: Working with PHP

<?php

$foo = 100;
$bar = 10;

if ($foo > $bar)
{
echo “I™m True!”;
}

<<

. 23
( 132 .)



>>