Create your own Functions - PHP

What is a Function?

A function is just a segment of code, separate from the rest of your code. You separate it because it's nice and handy, and you want to use it not once but over and over. It's a chunk of code that you think is useful, and want to use again. Functions save you from writing the code over and over. Here's an example.

Suppose you need to check text from a textbox. You want to trim any blank spaces from the left and right of the text that the user entered. So if they entered this:

" Bill Gates "

You want to turn it into this:

"Bill Gates"

But you also want to check if the user entered any text at all. You don't want the textbox to be completely blank!

You can use the PHP inbuilt function called trim( ). Like this:

$user_text = trim( $_POST['text1'] );

That will get rid of the white space in the text box. But it won't check if the text box is blank. You can add an if statement for that:

if ($user_text == "") {
error_message = "Blank textbox detected";
}

But what if you have lots of textboxes on your form? You'd have to have lots of if statements, and check each single variable for a blank string. That's a lot of code to write!
Rather than do that, you can create a single function, with one if statement that can be used for each blank string you need to check. Using a function means there's less code for you to write. And it's more efficient. We'll see how to write a function for the above scenario in a moment. But first, here's the basic syntax for a function.

function function_name() {
}

So you start by typing the word function. You then need to come up with a name for your function. You can call almost anything you like. It's just like a variable name. Next, you type two round brackets ( ). Finally, you need the two curly brackets as well { }. Whatever you function does goes between the curly brackets. Here's a simple example that just print something out:

function display_error_message() {
print "Error Detetceted";
}

In the example above, we've started with function. We've then called this particular functiondisplay_error_message. In between the curly brackets, there a print statement. Try it out with this script:

<?PHP
function display_error_message( ) {
print "Error Detetceted";
}
?>

Run your script and see what happens. You should find that nothing happens!
The reason that nothing happened is because a function is a separate piece of code. It doesn't run until you tell it to. Just loading the script won't work. It's like those inbuilt functions you used, such as trim. You can't use trim( ) unless you type out the name, and what you want PHP to trim. The same applies to your own functions – you have to "tell" PHP that you want to use a function that you wrote. You do this by simply typing out the name of your function. This is known as "calling" a function. Try this new version of the script.

<?PHP
function display_error_message() {
print "Error Detetceted";
}
display_error_message( );
?>

After the function, we've typed out the name again. This is enough to tell PHP to run our code segment. Now change your code to this, and see what happens:

<?PHP
display_error_message();
function display_error_message() {
print "Error Detetceted";
}
?>

If you have PHP 4 or above, you should see no difference – the function will still get executed with the name above or below the function. But for neatness and readability's sake, it's better to put all of your function either at the top or bottom of your scripts. Or better yet, in a separate PHP file. You can then use another inbuilt function called "Include" (which we'll get to soon)

There's a thing called scope in programming. This refers to where in your scripts a variable can be seen. If a variable can bee seen from anywhere, it's said to have global scope. In PHP, variables inside of functions can't be seen from outside of the function. And functions can't see variables if they are not part of the function itself. Try this variation of our script as an example:

<?PHP
$error_text = "Error Detetceted";
display_error_message();
function display_error_message( ) {
print $error_text;
}
?>

This time, we have set up a variable called $error_text to hold the text of our error message. This is set up outside of the function. Run the script, and you'll get a PHP error message about " Undefined variable".

Likewise, try this script:

<?PHP
display_error_message();
print $error_text;
function display_error_message() {
$error_text = "Error message";
}
?>

This time, the variable is inside the function, but we're trying to print it from outside the function. You still get an error message. Here's a correct version:

<?PHP
display_error_message();
function display_error_message() {
$error_text = "Error message";
print $error_text;
}
?>

Here, we have both the variable and the print statement set up inside of the function. The error message now prints.

Arguments

Functions can be handed variables, so that you can do something with what's inside of them. You pass the variable over to your functions by typing them inside of the round brackets of the function name. Here's a script similar to the one you saw earlier:

<?PHP
$error_text = "Error message";
display_error_message($error_text);
function display_error_message($error_text) {
print $error_text;
}
?>

The only difference is the that we now have something between the round brackets of our function:
function display_error_message($error_text) {
}

The name is the same, but we've put a variable in between the round brackets. This is the variable that we want to do something with. The one called $error_text. By typing a variable inside of the round brackets, you are setting up something called an argument. An argument is a variable or value that you want your function to deal with.
Notice how the function is called:

$error_text = "Error message";
display_error_message($error_text);

The first line puts something into the variable. But when you want to hand something to a function that has an argument, you need to type it between the round brackets of the function call. In our script, we're typing the name of the variable. But this would do just as well:
display_error_message("Error message");

Here, we're putting direct text between the round brackets. That works ok. But try it like this:

$error_text = "Error message";
display_error_message( );

You'll get an error message from PHP. Something like this:

"Warning: Missing argument 1 for display_error_message( )"

That's telling you that your function has been set up to take an argument, but that you've left the round brackets empty when you tried to call the function.

Your functions can have more than 1 argument. Just separate each argument with a comma. Like this:

function error_check($error_texterror_flag) {
}

To call this function, you'd then need to hand it two arguments:

$error_text = "Error message";
error_flag = 1;
error_check($error_texterror_flag);

If you only hand the above function 1 argument, you'd get error messages from PHP.
So, to recap:
  • To pass something to a function, create an argument
  • To call a function that has an argument, don't leave the round brackets empty
If you remember the script that we wanted to create earlier it was this:
  1. Get the text that a user entered in a textbox on a form
  2. Trim any blank spaces from the left and right of the text
  3. Check that what you have left is not a blank string
So we want to check that the textbox doesn't just contain this "". There has to be something in it, like "Bill Gates". Here's a script that does all three items on our list:

<?PHP
$user_text = trim("Bill Gates");
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == "") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>

Try it out. When you run the script, you should find that Text OK prints. Now change this line:
$user_text = trim("Bill Gates");
to this:
$user_text = trim("");

When you're creating your own functions, you may notice that they can be broken down in to two categories: functions that you can leave, and just let them do their jobs; and functions where you need to get an answer back. As an example, here's the two different categories in action:

print ("Get on with it!");
$string_length = strlen($string_length);

The print function is an example of a function that you can leave, and just let it do its job. You just tell it what to print and it gets on with it for you. But a function like strlen( ) is not. You need something back from it – the length of the string.

Suppose you had a function that worked out a 10 percent discount. But you only want to apply the discount if the customer spent over 100 pounds. You could create a function that is handed the amount spent. Then check to see if it's over a 100 pounds. If it is, the function calculates the discount; if not, don't apply the discount. But in both cases, you want the function to return the answer to your question – What do I charge this customer? Here's the script:

<?PHP
$total_spent = 120;
$order_total = calculate_total($total_spent);
print $order_total;
function calculate_total($total_spent) {
$discount = 0.1;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}
?>

The lines to concentrate on are the ones for the $total_spent variable. The code first sets up a total amount spent, which in practice may come from a form on a text box, or a hidden field:

$total_spent = 120;

The next line is our function call:

$order_total = calculate_total($total_spent);

The function call is now on the right of the equals sign ( = ). To the left of the equals sign is just a normal variable - $order_total . If you're setting up your function like this then you are asking PHP to return a value from your functions, and put the answer into a variable on the left of the equals sign. PHP will go off and calculate your function. When it's found an answer, it will try to return a value. The answer will be stored in the name of your function, calculate_total( ) for us. But look at the function itself, and the line at the end:

function calculate_total($total_spent) {
$discount = 0.1;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}

The last line is:
return $total_charged;

The return word tells PHP to return a value. The value it returns is whatever you have stored in the variable that comes after the word return. Here, were telling PHP to set the answer to the function called calculate_total( ) to whatever is stored in the variable we've called $total_charged. It's this that will get stored in our variable called $order_total.

If you're finding this a bit tricky, remember what a function is: a separate piece of code that does some work for you. It can either return a value, or not return a value. It depends entirely on your needs. But don't worry about the majority of the code above – just concentrate on the coloured parts.

In the script above, you'd want to get something back from the function, rather than letting it just print something out. If you ran the previous script, you'll notice that the function prints out the same thing twice. To stop that happening, we can get a return value, and put it in a variable. We can then check what is coming back from the function, to check what's in it.

Functions can be quite hard to get used, if you've never met them before. Another difficult part to understand is how values can change, or not change, depending on scope. Scope, if you recall, refers to where in your code a variable can be seen. If you just do this, for example:
$Variable_Value = 10;
example( );
function example() {
print $Variable_Value;
}

then you'll get a PHP error about "undefined variable". That's because the function called example( ) can't see what's inside of the variable called $Variable_Value.

In order for the function to be able to see what’s inside of the variable called $Variable_Value, you can set up the function to accept an argument. You'd then type the variable name between the round brackets, when you come to call it. Like this:

<?PHP
$Variable_Value = 10;
example($Variable_Value);
function example($Variable_Value) {
print $Variable_Value;
}
?>

If you run the code above, it now prints out the number ten. But it's important to bear in mind that you are just handing the function a copy of the variable. You're not effecting the original. As an example, change your code to this:

<?PHP
$Variable_Value = 10;
print "Before the function call = " . $Variable_Value . "<BR>";
example($Variable_Value);
print "After the function call = " . $Variable_Value;
function example($Variable_Value) {
$Variable_Value = $Variable_Value + 10;
print "Inside of the function = " . $Variable_Value . "<BR>";
}
?>

Here, we have three print statement: one before the call to the function, one inside of the function, and one after the function call. But we're printing out the value of the variable called $Variable_Value each time. Inside of the function, we're adding ten to the value of the variable. When you run the code, it will print out this:

Before the function call = 10
Inside of the function = 20
After the function call = 10

The important one is After the function call. Even though we changed the value of $Variable_Value inside of the function, it still print 10 after the function call! That's because the function was handed a copy, and NOT the original.

When you hand a function a copy of a variable, it's called passing the variable by value (just a copy). The alternative is to NOT pass a copy, but to refer back to the original. Make one small change to your script. This:

function example(&$Variable_Value) {

The only addition is a & character before the variable between round brackets. This tells PHP that you want to make changes to the original, and don't just want a copy. When you run the script, it now print out the following:

Before the function call = 10
Inside of the function = 20
After the function call = 20

After the function call, we now have a value of 20! So a change to the value of the variable outside the function has been made. When you makes changes to the original like this, it's called passing the variable by reference (don't just copy it – remember it).

Try not to worry about value and reference. Unless the answers you're getting back from your function are rather odd, that is!

PHP stores a list of information about the server. This will include things like, the browser the visitor is using, the IP address, and which web page the visitor came from. Here's a script to try with those three Server Variables:

$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
print "Referrer = " . $referrer . "<BR>";
print "Browser = " . $browser . "<BR>";
print "IP Adress = " . $ipAddress;

These are useful if you want to log your stats, or to ban a particular IP address! (If you run the script on a local machine, you may get an error for the referrer.)
So to get at the values in Server Variables, the syntax is this:

$_SERVER['Server_Variable']

You start with a dollar sign, then an underscore character ( $_ ). Then you add the word SERVER. In between square brackets, you type the name of the server variable you want to access. Surround this with either single or double quotes.

Because you are returning a value, you need to put all that on the right hand side of an equals sign. On the left of the equals sign ( = ), you need a variable to hold the string that is returned.

The server variables are held in an array (associative), so you can use a foreach loop to get a list of all available ones. Try this script:

<?PHP
foreach($_SERVER as $key_name => $key_value) {
print $key_name . " = " . $key_value . "<br>";
}
?>