PHP Functions

May 9th, 2012

In PHP, there are more than 700 built-in functions which are documented on the PHP site.
Functions help to keep code in a logical order and can prevent you duplicating code.
They are an important part of most programming languages. Functions in PHP are always enclosed by a pair of curly braces.

Create your own PHP Function

In PHP you can write your own functions.
Functions are only executed when they are called.
The following example simply adds two numbers together.


// A simple function to add two numbers together

function add_numbers($num1, $num2) {

	return ($num1 + $num2);


print (add_numbers(5, 10));


The output from this script should be 15 (5 + 10).
Lets have a look at what’s happening:

The function “add_numbers” has two variables within the set of brackets, called parameters.
When we call the function, we are passing two variables to the function. All the function does is add $num + $num2 and return the value.

Calling the function is just a case of calling add_numbers(5, 10).
The print function simply prints the result. We have a double set of brackets because the syntax of the print function is “print()”.