Defining and Using Functions in PHP

Share this article

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

Frequently Asked Questions about PHP Functions

What is the difference between built-in and user-defined functions in PHP?

Built-in functions are those that are already defined in PHP. They are part of the PHP core and can be used directly without any need for definition. Examples include echo(), print(), and var_dump(). On the other hand, user-defined functions are those that are created by the programmer. They are defined using the function keyword followed by a unique function name and parentheses for optional parameters.

How can I pass arguments to a PHP function?

Arguments can be passed to a PHP function within the parentheses that follow the function name. For example, in the function definition function addNumbers($num1, $num2), $num1 and $num2 are the arguments. When calling the function, you would pass the values for these arguments like this: addNumbers(3, 4).

What is the purpose of the return statement in a PHP function?

The return statement is used to end the execution of a function and send a value back to the calling code. It’s optional; if not provided, the function will return NULL. The return statement can be used to return any type of data, including arrays and objects.

Can a PHP function return multiple values?

While a PHP function can’t directly return multiple values, you can achieve this by returning an array or an object that contains multiple values. For example, you could return an array like this: return array($value1, $value2, $value3).

What are variable functions in PHP?

Variable functions in PHP are functions that can be assigned to a variable. This means you can create a variable with the name of a function and then call it as a function. For example, if you have a function named testFunction, you could do $func = ‘testFunction’; and then call it like this: $func().

How can I define a function inside another function in PHP?

In PHP, you can define a function inside another function. However, the inner function is only accessible and exists within the scope of the outer function. This means you can’t call the inner function outside of the outer function.

What is function recursion in PHP?

Function recursion in PHP is when a function calls itself. This can be useful for tasks that require looping through data in a specific way, such as traversing a complex data structure. However, recursion should be used carefully as it can lead to infinite loops if not properly controlled.

What are anonymous functions in PHP?

Anonymous functions, also known as closures, are functions without a specified name. They are most commonly used as callback functions passed to other functions or methods. You can assign an anonymous function to a variable and call it using the variable name.

How can I use default parameters in PHP functions?

Default parameters in PHP functions are used when you want to set a default value for a function’s argument. This value will be used if no argument value is provided when the function is called. You can set a default parameter by assigning a value to the argument in the function definition, like this: function testFunction($param1 = ‘default’).

What is the difference between declaring a function with and without the static keyword in PHP?

Declaring a function with the static keyword in PHP means that the function will retain its state between calls. This is useful when you want a function to remember the value of a variable from its previous call. Without the static keyword, the function will not remember the value of a variable once it has finished executing.

Iain TenchIain Tench
View Author

Iain Tench has worked in the IT industry for 30 years as a programmer, project manager (Prince2 Practitioner), consultant, and teacher. As a project manager, he specialized in integration projects mainly involving payment systems in the financial sector. He now teaches and has acquired a Masters degree in Internet Systems Development as well as a teaching qualification. Iain's specialized areas of teaching is web technologies, mainly programming in a variety of languages, HTML, CSS and database integration. He's also written a book about Dreamweaver CS3 for Hodder Education.

Beginner
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week