When you define a user-defined function, you specify how it should execute and what values (if any) it
should return. You can optionally give it parameters and tell it what to do with them.
The way to define a function in PHP is as follows:
function function_name (parameters) {
# function statements here
return variables # optional
}
Then you can invoke the function using the following:
function_name (parameters);
For example, imagine that you want a function to add a percentage to a number (such as adding sales
tax). You want to pass it two values: one the raw price and one the percentage:
function add_percent ($price, $percent) {
$newprice = $price * (1 + ($percent/100));
return $newprice;
}
Then you want to invoke it:
echo "The new price is ".add_percent (150, 25);
This would print
The new price is 187.5
Arrays
Understanding how arrays work in PHP is an essential step in learning how to access MySQL databases.
In PHP, sequentially indexed arrays contain elements starting at the "zeroth" element ($myarray[0]).
Arrays can also be string-indexed, as you'll see in a moment. You can get the number of elements in an
array by using the count() function (count($myarray)).
A sequentially indexed array can be populated in a number of ways. For example, you can write the
following:
$myarray[] = 'red';
$myarray[] = 'green';
$myarray[] = 'blue';
which is the same as
$myarray[0] = 'red';
$myarray[1] = 'green';
$myarray[2] = 'blue';
Then you can view the contents of the entire array by looping through it with a for loop:
for ($i=0; $i<count($myarray); $i++) {
echo "Element $i is ".$myarray[$i]."<br>\n";
}
This would produce the following output:
Element 0 is red
Element 1 is green
Element 2 is blue
You can also index arrays using strings: