. 38
( 132 .)



That™s easy enough. But what if you want the border to vary in given situations?
You can make the border a variable, and then in the function call specify the value
for border:

function start_table($border)
echo “<table border=$border>\n”;


Now suppose that most of the time you want the border to be 1, but that you
want to be able to change the border within the function call. The following does
the trick:

function start_table($border=1)
echo “<table border=$border>\n”;

Here $border has been given a default value of 1. But you can overwrite that
value by specifying a different value when calling the function. For example, if you
call the function with the following command, the table has a border of 2:


Once again, 1 is the default value, so if this function is called with the following
code the table border is 1:


If you know your HTML, you know that the table tag can have multiple attrib-
utes: cellspacing and cellpadding are two others. You can add those to the
function, along with default values:

function start_table($border=1, $cellspacing=2, $cellpadding=2)
echo “<table border=$border cellspacing=$cellspacing
202 Part II: Working with PHP

Then, in the call to this function you can alter any of these:


The table created with this command has a border of 4, cellspacing of 2, and
cellpadding of 5.

The values that the function accepts are known as arguments. So the
start_table function shown here takes three arguments. The more
pedantic members of the audience might point out that the values sent to
the function are arguments, while the values received by and used within
the function are parameters. Practically speaking, they™re the same thing,
and you see the words used interchangeably all the time.

When constructing functions, be aware that if you wish to change one of the
default values in your function call, you must specify all the arguments that pre-
cede it (that is, that occur to the left of it). For instance, the first command in the
following code produces an error. However, the second one works and creates a
table tag with a border of 4, cellspacing of 3, and cellpadding of 2.

//this will cause an error
start_table( ,5,5);
//this will work

Also, if you don™t specify a default value for an argument in your function defi-
nition, then you must supply a value for it when you call it. If you had written the
start_table() function like this:

function start_table($border=1, $cellspacing=2, $cellpadding)

Then this call . . .


would fail. You need to supply a value for $cellpadding, like this:


Functions can accept more than simple variables; you can pass any of the scalar
types (string, integer, double), any array (numeric, associative, or multidimensional),
resources (like a MySQL connection handle), or objects. You might want to make
Chapter 7: Writing Organized and Readable Code 203

use of a function that turns a PHP array (in other words, a list of stuff) into an
HTML unordered list (a visible list of stuff).

function create_ul($array)
echo “<ul>\n”;
foreach ($array as $value)
echo “<li>$value</li>\n”;
echo “</ul>\n”;

Returning values
Of course, your functions do more than print HTML. Functions can perform data-
base calls or mathematical computations or do some string handling. They can do
just about anything, and often you want to make the rest of the script aware of the
results of your function. You can do this by using the keyword return. When a
function hits the word return it leaves the function, and it returns whatever value
you specify ” a variable, a Boolean value (TRUE or FALSE), or nothing at all, if that™s
what you prefer. (Note: a plain ˜return;™ statement is equivalent to ˜return NULL;™.)

function basic_math($val_1, $val_2)
$added = $val_1 + $val_2;
return $added;

You can then call this function and print the results:

$added_value = basic_math(5,4);
echo $added_value;

If fact, the following works equally well:

echo basic_math(5,4);

Functions can return any variable type (strings, object, arrays, and the like), or,
in the case of database calls, they can return result identifiers. Additionally, func-
tions can return FALSE. If you read Chapter 5, you might remember that in PHP any
non-zero, non-false value is evaluated in an if statement as TRUE. So you might
want to improve the previous function by making sure the values passed can be
204 Part II: Working with PHP

function basic_math($val_1, $val_2)
if (!is_int($val_1) || !is_int($val_2))
return FALSE;
$added = $val_1 + $val_2;
return $added;

If either of the arguments in the call to this function is not an integer, the func-
tion returns FALSE and stops. A call to this improved function might look like this:

if (($added_value = basic_math(7, 5)) === FALSE)
echo “What exactly are you doing?”;
echo $added_value;

If the function returns a value (any value), that value is added. If not, a special
message is printed. Notice how this mimics the behavior of many of the PHP built-
in functions. Its purpose is to perform a task, and if it fails to do so, it returns FALSE.
Take a quick look at the following function. It™s a good example of how func-
tions can really save you time, headaches, and keystrokes. The mysql_query func-
tion is fine; it sends a query from PHP to MySQL and, if it succeeds, returns a result
identifier. If it fails, however, it does not automatically return any error informa-
tion. Unless you do a bit of digging, you won™t know what the problem was with
the query. So for every query in your applications (and there will be plenty), you
tack on an or die phrase:

mysql_query(“select * from table_name”) or die
(“Query failed:” . mysql_error());

But life gets quite a bit easier if you create a function like the following and then
send all of your queries through that function:

function safe_query ($query = “”)
if (empty($query)) { return FALSE; }
$result = mysql_query($query)
or die(“ack! query failed: “
Chapter 7: Writing Organized and Readable Code 205

return $result;

So your applications might include a file with this function on every page, and
then you can use safe_query() in place of mysql_query().

Using a variable number of arguments
One nice feature of PHP is that you can pass an indefinite number of arguments to
a function and then assign the list of arguments to an array. Consider the following

function print_input_fields()
$fields = func_get_args();
foreach ($fields as $field)
if (isset($GLOBALS[$field]))
$value = $GLOBALS[$field];
$value = ˜™;
print “ <tr>\n”;
print “ <td valign=top
print “ <td valign=top align=left><input type=text
name=$field size=40 value=\”$value\”></td>\n”;
print “ </tr>\n\n”;

The $GLOBALS array is discussed later in this chapter in the “Variable
scope” section.
206 Part II: Working with PHP

This function prints out form fields within a table. First, func_get_args() cre-
ates an associative array, with the name of the argument as the key. Then each form
field is printed out. This strategy is pretty convenient because you can call a func-
tion in a number of situations and vary the output by including as many arguments
as needed.
If you™re wondering how this might work if your function contains some
required parameters prior to the set of arguments that might vary, good for you.
That™s an excellent question.
Two other PHP functions work in such situations: func_num_args(), which
returns the number of arguments sent to a function, and func_get_arg(), which
returns a specific argument based on its numeric index, starting at 0. So, for exam-
ple, you might have a function that prints an HTML form with a variable number of
input fields, like the following:

function print_form($action=””, $method=”POST”)
if (empty($action)){return FALSE;}
echo “<form action=$action method=$method>”;
$numargs = func_num_args();
for ($i = 2; $i < $numargs; $i++)
echo “<input type=text name=” . func_get_arg($i). “>”;
echo “</form>”;

print_form(“myurl.php”, “”, “myfield1”, “myfiels2”);

Be aware that empty() might behave differently than you expect. It returns true
if the evaluated variable is not defined, or if it contains “”, 0, “0”, NULL, FALSE, or
an array with no elements.

Variable scope
To work with functions you need to understand how PHP handles variable scope.
Scope is an important topic in any programming language, and PHP is no different.
In PHP, variables assigned outside of functions are known as global variables.
These can be variables that you create, they can come from HTML form elements
through either GET or POST, or they can be any of the variables inherited from the
Apache environment. All globals are accessible from an array known as $GLOBALS.


. 38
( 132 .)