What are Functions in PHP

What are Functions in PHP

It’s good to encapsulate code you need to run over and over again inside of a function so you don’t have to type it out over and over. Code reuse and keeping it DRY (Don’t Repeat Yourself) is key to providing a maintainable application. A function is simply a piece of PHP code that you can call and it may or may not have parameters that you can send to it, and it also may or may not return a value. We like to give descriptive names to our functions so that we can infer what action they may provide us. Functions are the movers and shakers in PHP, they are the main piece of getting your software to actually do something. In this post we’ll take a closer look at User Defined Functions, Arguments to Functions, Returning Values from a Function, Recursive Functions, as well as Variable Functions. We have a lot to cover so let’s jump right in!

User Defined Functions

PHP has loads of built in functions and sometimes it seems overwhelming where to even begin. Thankfully we already covered the most used php string functions as well as the most used php array functions. Reading up on those will get you going with the key built in functions of the language. Right now we’re going to talk about making our very own functions for our special case use.

The syntax for creating a function is very easy. Let’s check it out:

function function_name() {
    // do stuff

The naming of the function is any string beginning with a letter or underscore followed by a combination of digits, letters, or underscores. Make it easy on yourself and choose simple descriptive naming for your functions, no need to get fancy. PHP functions are not case sensitive however it is best practice to always use all lowercase letters. Though they don’t have to, functions will usually return a value. This is done using the keyword return, and any number of return statements can be used in the function in condition checking scenarios. Once the return keyword is reached in the program, control goes back to the calling code along with the value produced by the expression in the function. For example:

function br() {
	echo '<br>';
	// optional return statement
function add($num1, $num2) {
	return $num1 + $num2;
	// returning a value

echo add(5, 4); // 9
br();           // <br>
echo add(4, 3); // 7

Arguments to Functions

Functions can accept a certain number of arguments by declaring them in the function definition. There are two different ways to pass parameters to a function and we’ll take a look at them now.

Passing by value

Usually parameters are passed by value in PHP, but you also have the option of passing by reference. The argument in the function is any valid expression which when evaluated assigns the value to the variable in the function.

function doublefail($value) {
	$value = $value * 2; // when this line runs $c retains 4
$c = 4;
echo $c; // 4

function doublefailreturn($value) {
	return $value = $value * 2;
$d = 10;
echo doublefailreturn($d); // returns 20
echo $d; // leaves $d set to 10

In the doublefail function, we use pass by value, so when the function runs, it doubles the copy of the variable, not the value of the caller’s variable like the doubleit function does. You could get what you want out of doublefail if you return the copy like in the last example.

Passing by Reference

You can override the scoping rules and have the function gain direct access to a variable by using pass by reference. To do this, you add an ampersand & to the front of the variable name in the parameter list.

function doubleit(&$value) {
	$value = $value * 2; // when this line runs $b gets set to 8
$b = 4;
echo $b; // 8
doubleit(7); // Fatal error: Only variables can be passed by reference

The doubleit function passes $value by reference, that is to say the actual value of $b instead of a copy of said value. This allows the function to modify the value directly and when we then echo out the value, we see it gets doubled from 4 to 8 successfully. Only variables can be supplied to parameters declared as passing by reference.

Variable Length Argument Lists

A function may need a variable number of arguments. To declare a function with a variable number of arguments, you leave out the parameter block entirely like this:

function awesomeFunction() {
// do awesome stuff

PHP gives you three functions to use in the function in order to get the parameters passed to it.

func_get_args() returns an array of all parameters provided to a function;
func_num_args() returns the number of parameters provided to a function;
func_get_arg() returns a specific argument from the parameter list.

For example:

$array = func_get_args();
$count = func_num_args();
$value = func_get_arg(argument_index);

In the following example, the add_arguments_lis() function takes in any number of arguments. It then loops over those arguments, adds to the total on each iteration, and returns the sum of all the values once complete. If no parameters are given, it will simply return false.

function add_arguments_list() {
	if(func_num_args() == 0) {
		return false;
	} else {
		$count = 0;
		for($i = 0; $i < func_num_args(); $i++) {
			$count += func_get_arg($i);
		return $count;
echo add_arguments_list(25, 50, 75); // outputs "150"

These functions cannot be directly used as a parameter to another function. You must first set a variable to the result of the function, and then use that in the function call.

Returning Values from a Function

PHP functions return only a single value with the return keyword:

function returnIt() {
    return 'It';

If you would like to return multiple values, we need to return an array:

function returnArray() {
    return array("Tom", 37, "Music");

or return an object:

class User {
	public $userid;
	public $name;
	public $status;

function GetUser($userid) {
	$userObj = new User();
	$userObj->userid = $userid;
	$userObj->name = 'Rick James';
	$userObj->status = 'Super Freak';
	return $userObj;

$newuser = GetUser(1);

If no return value is provided by a function, the function returns NULL.

Recursive Functions

A recursive function is a function that calls itself. Recursion sounds straightforward, but once you start working with it and try to really understand how it works, it can be very tricky.
To write a recursive function, you need to provide it with some means of return or else it will keep calling itself until the program crashes. This is known as the base case. The base case is often found in a conditional like an if statement that will stop the recursion once a condition is met. You also need a recursive case. This is where the recursion, or looping if you will, takes place. The function is called on itself using the recursive case.


The textbook example of recursion is the factorial example. The factorial function symbol(!) means to multiply a series of descending non negative numbers like so:

4! = 4 × 3 × 2 × 1 = 24
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
8! = 8 x 7 × 6 × 5 × 4 × 3 × 2 × 1 = 40320

Instead of manually doing this math, we could create a function that accepts a number, and then calculates the factorial by recursion:

function factorial($number) { 
    if ($number < 2) { 
        return 1;  // base case
    } else { 
        return ($number * factorial($number-1));  // recursive case


Many tutorials leave out the fact that this comes from the formula n! = n × (n-1)! which means “the factorial of any number is that number times the factorial of (1 smaller than that number)

We’ll go step by step through this function using the number 4 to keep it manageable. To do this I have put the code above into eclipse pdt and will step into each execution step.

1. The function definition gets read into memory
2. factorial(4); is called.
3. $number is now 4 so we move to the else clause
4. Recursion! The function calls itself passing in 3 as it’s parameter
5. $number is now 3 so we move to the else clause
6. Recursion! The function calls itself passing in 2 as it’s parameter
7. $number is now 2 so we move to the else clause
8. Recursion! The function calls itself passing in 1 as it’s parameter
9. $number is now 1 so we return 1
10. echo factorial(4); now outputs the answer of 24.

Variable Functions

Variable functions will be useful when we cover object-oriented programming. In the meantime, we’ll look at the basics of how variable functions work. A variable function is simply where you assign a function name to a variable and then you can call that function by using the variable name.

Let’s remember our example of the factorial function. We could create a random variable name and assign that function to it using the following syntax:

$fact = 'factorial';
//We can then call that function like so
echo $fact(5); //120

Note that language constructs such as echo() and isset() cannot be called through variable functions:

$variable = "echo";
$variable("hello, world"); // does not work

Now that we have a good grip on functions in PHP, let’s whip up some PHP String Helper Functions to help with common string manipulation tasks!

Thank you for reading What are Functions in PHP – If you found this post helpful, Please do share using the buttons below!