PHP Functions

A function is simply a bit of code that we keep on-hand ready to use when needed.

Each function has its own unique name, and will always begin with the word “function”. Makes sense, huh?

Although learning and understanding functions may seem like a daunting task, by taking it one step at a time you will have no problem catching on.

When To Use PHP Functions

There are many instances you will come across where it would be proper for you to use functions. For example, if you will be displaying the tagline of your website over and over again, you can create a function for it, so that it will “be on-hand ready to use when needed”.

Creating A PHP Function

Now that we have a basic understanding of what a function is and when we could use it, we can create a function which will display our website’s tagline whenever we need to:


function tagline(){
echo "Where Fortunes Are Made";
}

The above function is simple enough: we first named the function “tagline”, then defined what bit of code that function contains, which is “Where Fortunes Are Made”.

Take note that when naming a function, the name can not begin with a number.

Using A PHP Function

Now that the function has been created, we can use it:


echo "Welcome to JWRmedia.com
";
tagline();

This bit of code would display:

Welcome to JWRmedia.com
Where Fortunes Are Made

Notice how much easier it is to use “tagline();” rather than typing the entire echo over and over again. This is especially true when your function holds quite a much larger amount of code than our example!

Functions, of course do not end with holding a small line of text. Functions can incorporate many lines of code.

Function Parameters

The above example is obviously very basic. To make our function more dynamic, we can add a function parameter.

Let’s say that we have three people which have access to a certain page: Larry, Moe and Curly. Using a PHP function, we can customize our tagline based on their name.


function tagline($name){
echo "Where ". $name . " Makes A Fortune
";
}

name("Larry");
name("Moe");
name("Curly");

This bit of code would display:

Where Larry Makes A Fortune
Where Moe Makes A Fortune
Where Curly Makes A Fortune