Defining and Using Functions in PHP

Let’s start by defining the word “function.” A function is a self-contained piece of code which carries out a particular task (or function!). A key benefit of using functions is that they are reusable; if you have a task that needs to be performed a number of times, a function is an ideal solution. They can be either defined by you or by PHP (PHP has a rich collection of built-in functions). This article will focus on programmer-defined functions but will touch briefly on PHP’s functions to complete the picture.

Defining a Function

So what does the syntax for defining a function look like? Here is a simple example:

<?php
function addNumbers($num1, $num2) {
    $result = $num1 + $num2;
    return $result;
}

The keyword function lets PHP know that what follows is, you’ve guessed it, a function definition. Next, addNumbers is the name of the function. The open and close parentheses hold arguments (sometimes referred to as parameters), the values you’ll pass to the function when you invoke it. Functions do not have to accept arguments, in which case the parentheses would be empty. Here the variables $num1 and $num2 are arbitrary names and are referenced though within the function.

Note that the two statement lines within the function are contained within brackets. These lines make up what are known as the function’s body. The statements here are very simple: the first takes the values passed to the function as $num1 and $num2, adds them together and stores the resulting value in $result. The second line then uses return to pass the value of $result back to the calling statement.

As with arguments, functions do not have to return values either. They might be used to carry out a calculation which is printed, for example. However, it is important to understand the concept of returning a value from a function since you will probably return values more often than not.

Functions will not be executed until you write some code to do so. To invoke the sample function, you would use a statement like this:

<?php
$total = addNumbers($loanAmount, $interestAmount);

What does this mean? Well, the code after the = invokes or calls the function and causes its code to run. The values passed to the function are held in the two variables $loanAmount and $interestAmount. Notice that these names do not correspond with the argument names used when defining the function, i.e. $num1 and $num2. This doesn’t matter. The important point is that the function has been defined as having two arguments and you have supplied two arguments when executing the function. For obvious reasons, the values held in the variables $loanAmount and $interestAmount should be numeric since the function performs a mathematical operation.

Because return has been used in the function, the total held in $result will be passed back to the statement which executes the function. In this case the value will be assigned to $total.

When naming a function, the name should be unique. It can be made up of letters, numbers, and the underscore, but must not start with a digit (the same rules for naming a variable). Thus, addNumbers and add_numbers are valid function names, while add numbers is not (embedded space) nor is 12add_numbers (starts with a digit). Naming your function abc123 is syntactically correct but unhelpful. Ideally, the function name should be meaningful too.

As I mentioned at the start of this article, PHP defines some functions as well. It’s always worth looking to see if PHP has a function to do what you want before writing your own. But how do you know if you need to define your own function or if PHP provides one that does what you need? The answer is to familiarize yourself with the online documentation. For example, you might wish to format a date. Go first to www.php.net and in search box type “date”. You’ll be presented with information on the date() function and, on the left-hand side, a list of related date and time functions.

Organizing Functions

Now that you’ve seen the syntax of a function, the next step is to decide where you should put the function code.

Because functions are only executed on request, you could place them together at the beginning of your code. Here’s an example:

<?php
function hello() {
    print "<h1>HELLO!</h1>";
    print "<p>Welcome to my web site</p>";
}

function printBreak($text) {
    print "$text<br>";
}

function addNumbers($num1, $num2) {
     return $num1 + $num2;
}

hello();
printBreak("This is a line");
print addNumbers(3.75, 5.645);

This code displays the following output in a browser:

function test output

The three functions are defined and then the code which executes them follows. Note that the function hello() does not have any arguments as its purpose is just to print a welcome message. The function printBreak() is a similar example – text is passed as an argument which is referenced in the function as the variable $text. Finally there is a slightly modified version of the addNumbers() function from earlier.

At this point, the functions are only available in the script in which they have been defined. If you want to make them accessible to all of your scripts, it’s a better idea to place them in a separate file and include them. This approach means that any changes required to your functions later can be made only be made in one place, rather than having to amend multiple scripts.

Move the three functions into their own file named functions.php. Then, revise the example to use require. It should now look like this:

<?php
require "functions.php";

hello();
printBreak("This is a line");
print addNums(3.75, 5.645);

Accepting a Variable Number of Arguments

So far you’ve dealt only with functions which accept a fixed number of arguments. If you pass only one argument when two are required, you will see a warning message like this:

Warning: Missing argument 2 for addNumbers() called in C:xampphtdocssitepointfunctions.php on line 17 and defined in C:xampphtdocssitepointfunctions.php on line 9

There may be circumstances when you want to pass a variable number of arguments – for example, you may need to calculate an average value from a range of numbers. In this case, the function would not define any arguments; instead, the number of values passed can be ascertained by using the PHP function func_num_args(). Another PHP function, func_get_arg(), allows you to retrieve the values passed into your function.

Here is an example which has been annotated with comments:

<?php
function calcAverage() {
    // initialize value to be used in calculation
    $total = 0;							

    // find out how many arguments were given
    $arguments = func_num_args();     	

    // loop to process each argument separately
    for ($i = 0; $i < $arguments; $i++) {
        // add the value in the current argument to the total
        $total += func_get_arg($i);
    }

    // after adding all arguments, calculate the average
    $average = $total / $arguments;		

    // return the average
    return $average;
}

// invoke the function with 5 arguments
echo calcAverage(44, 55, 66, 77, 88);			

// invoke the function with 8 arguments
echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7);

The function calcAverage() is executed twice, with a different numbers of arguments each time. Within calcAverage(), the function func_num_args() is called to determine the number of arguments that were passed in. The for loop, with which you may or may not be familiar with at this stage, retrieves each argument in turn using func_get_arg() and increments the total in $total. When all of the arguments have been retrieved and processed, the average value is calculated, returned, and printed using echo.

Summary

Let’s recap on some of the key concepts of functions:

  • Easier maintenance – use functions so you don’t repeat code for common tasks.
  • Reusability – functions can be used within individual scripts and across multiple scripts.
  • Flexibility – functions are flexible, accepting a specific number of arguments, or a variable number of arguments with func_num_args() and func_get_arg().
  • Improved Readability – separating functionality into functions streamlines your code and improves its readability.

You should now be equipped to create your own functions or find relevant ones from PHP’s extensive selection.

Image via kentoh / Shutterstock

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Joseph Myalla

    Great Article

  • http://www.georgedina.info George Dina

    Great job.
    I think you should have talked also about how global variables are managed in functions.

  • http://www.serveradminblog.com Mangia

    I agree with George about global vars inside functions…

  • http://www.affordablewebsitepublishing.com Alex

    Thanks for the article. I had never heard of func_num_args() before…I have always used an array. A tip for those just getting into functions: Write your functions to return a value, not print it directly. It will make your functions easier to re-purpose, and it is important to separate your logic from presentation.
    Thanks again.

    • Dave

      I had also never heard of func_num_args(), reminds me of argc and argv[]

  • Bob

    Good starter. If one wants to go further then the mention of globals would be a plus. Error handling, exception handling and of course good comments are a plus as well.
    Similar to Alex, I used arrays. At least until now.

    Good Job!

  • http://ukfolkfestivals.co.uk Dr John

    The examples given all involve calculations, but functions can be used to output html code as well.
    So you can create a set of functions to build the head of your html document. eg startHead(), makeTitle($title), insertCSS($cssfile), insertJQuery(), insertJavascript($jsfile), closeHead(), startBody(). Certainly takes the tedium out of writing the html, and the functions can become very reusable (and used more than once when building the head, in the case of the insertXYZ($variable) ones). I found it was much more flexible to use a small set of functions one after the other rather than one large function that combined all the code, as I could then add whatever number of css or javascript files were required.