Tutorials

Learn web design and programming with our free video and text tutorials.

Web Designer? Design and market your own professional website with easy-to-use tools.

PHP Functions

What is a Function in PHP?

Functions provide a way to group related actions together and to be able to repeatedly execute them without retyping the code.

PHP has over 700 functions that are already built-in to PHP and PHP also allows you to create your own functions.

How to Create PHP Functions

PHP allows you to create your own functions. To create a new function, you must first use the function keyword. After the function keyword, is the name of the function. Function names can include letters, number or the underscore symbol (_) and can only begin with eith a letter or an underscore symbol. The function name is then followed by a set of paranthesis (()) which are followed by a set of curly braces ({}). Within the parenthesis goes the argument(s) of the function and within the curly braces goes the code to be executed when the function is called.

Below is the basic syntax of a function.

<?php
function functionName () {
// code to be executed when the function is called
}
?>

To call a function, you type the name of the function followed a parenthesis.

The PHP code below creates a function which will be named helloWorld, and then calls the function.

<?php
function helloWorld() {
echo 'Hello World!';
}

helloWorld();
?>

The PHP code would output the text "Hello World!" to your web browser.

built-in PHP Functions

PHP has over 700 built-in functions. The full list of built-in PHP functions can be found at http://php.net/quickref.php.

An example of a built-in PHP function is the phpinfo function. phpinfo is a globally accessible function that accepts no arguments and returns no results. What the phpinfo function does is output detailed information about the current PHP installation on your web server.

Copy the PHP script below into a new php file. If you have PHP installed on your computer, you can veiw the file web server document root or you can upload the file to your web server and view the web page that is created.

<?php
phpinfo();
?>

The image below is an example of what the phpinfo function will output.

php tutorial image

Passing Parameters to a Function

You can pass parameters (also called arguments) to all functions that you create and to some built-in PHP functions. A parameter within a function is just like a variable. The parameters are listed within the parenthesis. If there is more than 1 parameter, each parameter is seperated by a comma.

The PHP script below has 1 parameter listed.

<?php
function userName($user) {
return "Hello, $user";
}
echo userName(John);
echo "<br />";
echo userName(Mike);
echo "<br />";
echo userName(Gina);
?>

The PHP script above would output the text "Hello, John" to the screen.