Specifications
FIGURE 5.4
This HTML table is the result of calling create_table().
Passing a parameter allowed us to get data that was created outside the function—in this case,
the array $data—into the function.
As with built-in functions, user-defined functions can have multiple parameters and optional
parameters. We can improve our create_table() function in many ways, but one way might
be to allow the caller to specify the border or other attributes of the table. Here is an improved
version of the function. It is very similar, but allows us to optionally set the table’s border
width, cellspacing, and cellpadding.
function create_table2( $data, $border =1, $cellpadding = 4, $cellspacing = 4 )
{
echo “<table border = $border cellpadding = $cellpadding”
.” cellspacing = $cellspacing>”;
reset($data);
$value = current($data);
while ($value)
{
echo “<tr><td>$value</td></tr>\n”;
$value = next($data);
}
echo “</table>”;
}
The first parameter for create_table2() is still required. The next three are optional because
we have defined default values for them. We can create very similar output to that shown in
Figure 5.4 with this call to create_table2().
create_table2($my_array);
If we want the same data displayed in a more spread out style, we could call our new function
as follows:
create_table2($my_array, 3, 8, 8);
Reusing Code and Writing Functions
C
HAPTER 5
5
REUSING CODE
AND
WRITING
FUNCTIONS
135
07 7842 CH05 3/6/01 3:35 PM Page 135