A Wolf in the Library

Understanding PHP functions

This tutorial assumes you already an understanding of the most basic PHP elements.

What is a function?

In its simplest form a function is a named piece of code you can use to perform an action to a specific variable or variables. Once the fucntion is declared on a page, it can be called up whenever you need it again.

The Syntax

function func_name ($variable(s)) {
do something to the variable(s);
}

A Simple Function in Action.

<?php
function double ($number) {
$double_num = $number * 2 ;
echo $double_num;
}
?>

All functions are declared with the function command followed by the name of the function, which in this case is double. You'll notice the variable $number in the brackets. This is a place holder for the variable that will actually be sent to the function.
This function double takes the value $number and multiplies it by two then stores it in $double_num . Finally is it displays the value of $double_num.

So if the value of $number was 4, this function would echo 8.

How to Call a Function Once It's Defined

To call the above function you would simply need to write the following code between your <?php ?> code brackets.

<?php
double (27);
?>

This would return the value 54.
Notice I used 27 in the brackets. I could have just as easily used a variable as in the following example. Remember the variable must have a declared value before it can be used in the function.

<?php
$my_number = 8;
double ($my_number);
?>

This would return the value 16.

Things To Be Aware Of

Sometimes you might want the value of a function to be used somewhere else in your code. In the examples above, if you tried to use the $double_num in another part of your code. So you type the following:

<?php
echo $double_num;
?>

This will return an error telling you $double_num is an undefined variable. Why? A variable declared within a function is only useable within that function unless declared as a global variable. You probably won't need to do this very often but if you do it is shown in the sample below.

<?php
function double ($num) {
global $double_num;
$double_num = $num * 2;
echo $double_num;
}
?>

So now if you echo $double_num, it will return the last value of $double_num.

<?php
double (7);
echo "<br />";
double (14);
echo "<br />";
echo $double_num;
?>

The above will return
14
28
28

Until something is done to $double_num, it will remain 28.