A function can be most simply described as a shortcut to executing some oft-used code.
For example, if I were to take the following:
<?php
if ($do == 'form') {
?>
<table><tr><td>Page #1</td></tr>
<tr><td><input type="text" name="name1"></td></tr>
<tr><td><input type="text" name="site1"></td></tr></table>
<table><tr><td>Page #2</td></tr>
<tr><td><input type="text" name="name2"></td></tr>
<tr><td><input type="text" name="site2"></td></tr></table>
<table><tr><td>Page #3</td></tr>
<tr><td><input type="text" name="name3"></td></tr>
<tr><td><input type="text" name="site3"></td></tr></table>
<?php
}
?>
Now, you can see that the code is really duplicated three times with a subtle difference - the number of the page. I could easily put this into a function, like so:
<?php
function showtable($pagenum) {
?>
<table><tr><td>Page #<?=pagenum?></td></tr>
<tr><td><input type="text" name="name<?=pagenum?>"></td></tr>
<tr><td><input type="text" name="site<?=pagenum?>"></td></tr></table>
<?php
}
$total = 5;
for ($pagenumber = 1;$pagenumber < $total; $pagenumber++) {
// repeat until $pagenumber = 5, increasing $pagenumber after each pass
showtable($pagenumber);
}
?>
See how much cleaner and concise the second example is? Plus, if I need to use the same table elsewhere in my script, no more copy & paste, I simply use the function.
When defining functions, you can optionally define what are called arguments. Usually you will need to include at least one argument unless your code is self-sustaining - that is, it doesn't need input from the main script to return information. In the above example, $pagenum is an argument. As you see, you pass the argument to the function when calling the function, as in showtable($pagenumber). You can also hardcode the value of an argument in your script, such as showtable(5) to send the number 5 as the page number. Inside the function, to get the value of the argument, you use whatever you called the argument when defining the function. In the above case, I defined the function with showtable ($pagenum) so I use $pagenum inside my function to reference the argument.
You can also make arguments optional. Simply give a default value to the argument when defining the function. e.g.
showtable($pagenum=5) {
would mean that if you called showtable() it would use 5 as the page number. If you pass it a value, as in showtable($pagenumber), it will use the value you pass instead of the default. Usually if you are defining several arguments, you put the optional ones at the end so you can leave them off if you don't need them. Otherwise, if you have several required arguments and an optional one and you put the optional one in the middle, you must pass the optional one regardless of whether it is different than the default.
PHP itself has hundreds of built-in functions. Even something as simple as time() is a function. In the case of time(), it takes no arguments - it simply returns the current time in UNIX timestamp format.