Please wait

Functions

In PHP, a function is a set of instructions that perform a specific task, like baking a cake based on a recipe, that you can reuse throughout your program without having to repeat the same instructions over and over again, making your code easier to write, read, and maintain.

For example, just like a cake recipe specifies a list of ingredients and instructions to follow to bake a cake, a PHP function specifies a list of input arguments (if any) and a series of actions to perform and returns a result (if any), allowing you to call it whenever you need to perform that specific task, without having to write the same code from scratch every time.

Defining a Function

In PHP, you can define a function using the function keyword, followed by the name of the function, a set of parentheses, and a pair of curly braces that enclose the body of the function. Here's an example of a function that adds two numbers:

function sum() {
  $result = 5 + 5;
  echo $result;
}

In this example, the function is named sum. Inside the function, we declare a variable called $result that holds the sum of two numbers. Lastly, we're echoing the result.

Function names

Function names must follow a few rules:

  • Function names must start with a letter or underscore (_).
  • Function names can only contain letters, numbers, and underscores (_).
  • Function names are case-insensitive, so my_function() and MY_FUNCTION() refer to the same function.
  • Function names cannot be the same as PHP reserved keywords, such as if, echo, or function.

Valid names

Here are some examples of valid function names in PHP:

function my_function() {
  // function code here
}
 
function add_numbers() {
  // function code here
}
 
function _private_function() {
  // function code here
}

Invalid names

And here are some examples of invalid function names in PHP:

function 123_function() {
  // invalid function name
}
 
function if() {
  // invalid function name (reserved keyword)
}

It's generally a good idea to choose function names that are descriptive and easy to remember to make your code more readable and maintainable.

Calling a Function

To use a function, you simply call it by its name, followed by a set of parentheses. Here's an example of how to call the sum function we defined earlier:

sum();

In this example, we're calling the sum function. As a result, the page will output the following:

10

Order of Execution

A function in PHP (and in many other programming languages) is essentially a block of code that is defined to perform a specific task. It is not executed immediately when it is defined. Instead, it is executed when it is specifically called.

It's important to understand this concept as most developers define their functions first before rendering content. Here is a simple example:

// Define the function
function sayHello() {
    echo "Hello, World!";
}
 
// Some other lines of code
echo "This is some other code.";
 
// Call the function
sayHello();

In this script:

  1. The sayHello function is defined. It's designed to output the text "Hello, World!" when it's called. But at this point, it's not called yet, so it does nothing.
  2. The script then outputs "This is some other code.". It does this immediately, because this is not inside a function.
  3. Finally, the sayHello function is called. At this point, the code inside the function (i.e., echo "Hello, World!";) is executed, and "Hello, World!" is outputted.

So, when you run this script, you'll see:

This is some other code.
Hello, World!

Pass Arguments to a Function

In programming, an argument is a value that is passed to a function when it is called. In PHP, a function can accept any number of arguments, depending on the requirements of the function.

When you define a function, you can specify any number of input arguments that the function should accept. To pass values to these input arguments when you call the function, simply include them inside the set of parentheses after the function name, separated by commas. Here's an example of our sum function that accepts two numbers instead of hardcoding the numbers into the function:

function sum($num1, $num2) {
  $result = $num1 + $num2;
  echo $result;
}

In this example, the sum function takes two input arguments: $num1 (an integer) and $num2 (an integer). By accepting this information, the $result variable can store a different value each time the function is called. Our function becomes more flexible.

To call this function and pass in values for the input arguments, we would do something like this:

sum(5, 5);
sum(10, 4);
sum(2, 1);

In this example, we're calling the sum function three times with different numbers. As a result, we'll get the following output:

10
14
3

Parameter vs. arguments

In PHP (and in programming in general), the terms "parameter" and "argument" are often used interchangeably, but they do have slightly different meanings:

  • A parameter is a variable that is declared in the function definition and represents a value that the function expects to receive when it is called.
  • An argument is the actual value that is passed to the function when it is called and is assigned to the corresponding parameter variable.

For example, in the following PHP function definition, $num1 and $num2 are parameters:

function sum($num1, $num2) {
  $result = $num1 + $num2;
  echo $result;
}

And when we call the sum function with the values 5 and 3, 5 and 3 are arguments:

sum(5, 3);

So in this example, $num1 and $num2 are the parameters of the sum function, and 5 and 3 are the arguments that are passed to the function when it is called.

Default parameter values

Default parameter values are input arguments that have a pre-defined default value in case the caller of the function doesn't provide a value for that argument.

You can specify a default value for a parameter by assigning it in the function definition. Here's an example of a function with a default parameter:

function greet($name = 'friend') {
  echo "Hello, {$name}!";
}

In this example, we're defining a function called greet that takes one input argument, $name. We've assigned a default value of 'friend' to the $name parameter, which means that if the caller of the function doesn't provide a value for $name, the default value of 'friend' will be used.

If we call the greet function with a value for $name, that value will be used instead of the default:

greet('John');

In this example, we're calling the greet function and passing in the value 'John' as the input argument. The function will use the provided value instead of the default value of 'friend', and will output:

Hello, John!

If we call the greet function without a value for $name, the default value of 'friend' will be used:

greet(); // Outputs: Hello, friend!

Output:

Hello, friend!

Default parameters are useful when you want to make a function more flexible and allow callers to override default behavior without requiring them to provide a value for every input argument.

Return a Value from a Function

Functions are capable of producing a new value. Values produced by a function can be returned. A return value is a value that a function sends back to the code that called it. When you define a function, you can use the return keyword to specify the value that the function should return when it completes its task.

Return values are useful because they allow you to use the result of a function in other parts of your code. You may not always want to immediately output content onto the page. Sometimes, you may want to calculate a brand-new value to perform other actions.

For example, let's update our sum function from earlier to return the calculation instead of immediately echoing the result.

function sum($num1, $num2) {
  $result = $num1 + $num2;
  return $result;
}

In this example, we're defining a function called sum that takes two input arguments, $num1 and $num2. Inside the function, we're calculating the sum of the parameters by adding them together and storing the result in a variable called $result. Then, we're using the return keyword to send the value of $result back to the code that called the function.

Here's an example of how you can call this function and use the returned value:

$sum = sum(10, 5);

In this example, we're calling the sum function and passing in the values 10 and 5 as the input arguments. The function will add these two numbers together and return the result, which we're storing in a variable called $sum.

Returning values from a function

When you return a value from a function, the function stops running. So, be careful of writing logic after a return statement unless you don't want the code to be executed further.

Exercises

Exercise #1

Write a function called multiply_numbers that takes two input arguments, $num1 and $num2, and returns the product of the two numbers.

Exercise #2

The following function returns true if the parameter $age is greater than 18. Otherwise it asks for a confirmation and returns its result:

function checkAge($age) {
  if ($age > 18) {
    return true;
  } else {
    return 'Did parents allow you?';
  }
}

Will the function work differently if else is removed?

function checkAge($age) {
  if ($age > 18) {
    return true;
  }
 
  return 'Did parents allow you?';
}

Is there any difference in the behavior of these two variants?

Exercise #3

The following function returns true if the parameter $age is greater than 18. Otherwise it asks for a confirmation and returns its result.

function checkAge($age) {
  if ($age > 18) {
    return true;
  } else {
    return 'Did parents allow you?';
  }
}

Rewrite it, to perform the same, but without if, in a single line. (Hint: you can use a ternary operator)

Exercise #4

Write a function min($a,$b) which returns the least of two numbers $a and $b.

For instance:

min(2, 5); // returns 2
min(3, -1); // returns -1
min(1, 1); // returns 1

Exercise #5

Write a function powCustom($x,$n) that returns $x in power $n. Or, in other words, multiplies $x by itself $n times and returns the result.

Examples:

powCustom(3, 2); // Returns: 9
powCustom(3, 3); // Returns: 27
powCustom(1, 100); // Returns: 1

Key takeaways

  • A function is a block of code that performs a specific task.
  • Functions are defined using the function keyword, followed by the name of the function, input arguments in parentheses (optional), and the code to be executed in curly braces.
  • Parameters are input arguments that are passed to a function.
  • Parameters are defined in the function definition, and they specify the expected data type and name of the input argument.
  • Return values are values that a function sends back to the code that called it.
  • Return values are specified using the return keyword in the function code.
  • Return values are useful because they allow you to use the result of a function in other parts of your code.

Comments

Please read this before commenting