Lesson 9: Functions

In previous lessons you have learned to use functions like date() and array(). In this lesson, you will learn to create your own functions using function.

What is a function?

A function process inputs and returns an output. It can be useful if, for example, you have a wide range of data you have processed or if you have calculations or routines that must be performed many times.

A function has the following syntax:

Function Name(list of parameters) {
Statement
}

This way, we can make a very simple function that can add the value 1 to a number. It could look like this:

function AddOne($x) { $x = $x + 1; echo $x;}

Our function is named AddOne and must be called with a number - e.g. 34....

echo AddOne(34);

... which (surprise!) will return 35.

The example above processes a number, but functions can work with text, dates or anything else. You can also create functions that are called by many different parameters. In this lesson you will see different examples of functions.

Example 1: Function with more parameters

As mentioned above, you can easily create a function that can be called with more parameters. In the next example, we'll create a function that is called with three numbers and then returns the value of the three numbers added together:

Please note how '$arrMonth' and '$EnglishDateTime' are constructed over several lines. This is done so that users with a low screen resolution can better see the example. The method has no effect on the code itself.

The function above works on all web servers regardless of language. This means that you can use such a function if your website, for example, is hosted on a French server, but you want English dates.

At this stage, we will not go into more depth with functions, but now you know a little about how functions work.