Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Functions with Parameters and Return Values

Recommended resources

Hello! Welcome back to your PHP fundamentals refresher.

In our last lesson, we covered loops, which are fantastic for making your code efficient at performing repetitive tasks. Now, we'll take the next logical step in structuring our code: making it reusable. As you build more complex web applications, you'll find yourself writing the same logic in multiple places. Functions are the solution to this problem.

This lesson is all about how to create and call functions with parameters and return values. By bundling code into functions, you make your programs more organized, easier to read, and simpler to debug. This is a foundational practice for any professional developer.

1. What is a Function?

Think of a function as a named block of code that performs a specific task. You define it once, and then you can "call" or "invoke" it whenever you need that task performed. This follows the DRY (Don't Repeat Yourself) principle, a cornerstone of good programming.

The basic syntax to define a function is:

function functionName() {
    // Code to be executed
}

And to use it, you simply call it by its name:

functionName();

Let's watch a quick video that introduces this core idea.

PHP functions explained

This first video from Bro Code demonstrates the basic syntax for creating and calling a simple function.

Watch from 00:30 to 02:09. Notice how a block of code to sing 'Happy Birthday' is defined once and then called multiple times.


2. Passing Data to Functions with Parameters

Functions become truly powerful when you can pass data into them. This allows a single function to operate on different inputs, making it highly flexible.

  • Parameter: A variable listed in the function's definition. It's a placeholder for the data the function expects to receive.
  • Argument: The actual value or variable that you pass to the function when you call it.

Here is a visual example of a function that takes two parameters, adds them, and returns the result.

PHP Function with Parameters and Return Value Example
This image shows the complete lifecycle: a function `getTotal` is defined with `$param1` and `$param2` as placeholders. It's then called with the arguments `30` and `50`, and the returned value `80` is displayed.

To see this in action, the next part of the Bro Code video provides a clear example.

PHP functions explained

This segment explains how to define parameters in your function and pass arguments to it when you call it.

Watch from 02:09 to 04:29. Pay attention to how the arguments ('SpongeBob', 30) are passed to the function and assigned to the parameters ($first_name, $age).


3. Getting Results Back: The return Statement

While some functions just perform an action (like printing to the screen), many are designed to compute a value and send it back to the code that called it. This is done using the return statement.

When a return statement is encountered, the function immediately stops executing and sends the specified value back.

A common point of confusion for beginners is the difference between echo and return:

  • echo: Immediately prints a value to the output (e.g., the browser). It does not send any value back to the calling code.
  • return: Sends a value back to the calling code. The calling code is then responsible for what to do with that value (e.g., store it in a variable, print it, or use it in another calculation).

PHP Functions Tutorial - Learn PHP Programming

This video from Clever Techie clearly illustrates the important difference between returning a value and directly printing it inside a function.

Watch from 01:02 to 02:37. Notice how the returned value from the first function needs an echo to be displayed, while the second function prints its result directly.

Once you have a returned value, you can use it just like any other value:

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

$sum = add(10, 5); // The returned value (15) is stored in the $sum variable.
echo $sum; // Outputs: 15

// You can also use it directly in an expression
echo "The total is: " . add(20, 30); // Outputs: The total is: 50
Test your understanding!

Write a PHP function named calculateArea that takes two parameters, $width and $height. The function should calculate the area of a rectangle (width * height) and return the result.

Then, call this function with a width of 10 and a height of 8, store the result in a variable called $area, and print the variable to the screen.

Show answer
<?php

// Define the function
function calculateArea($width, $height) {
    return $width * $height;
}

// Call the function and store the result
$area = calculateArea(10, 8);

// Print the result
echo "The area of the rectangle is: " . $area;

// Expected output: The area of the rectangle is: 80
?>

4. Making Functions More Flexible and Robust

You can improve your functions by providing default behaviors and ensuring they receive the correct type of data.

Default Parameter Values

You can make a parameter optional by providing it with a default value. If the function is called without that argument, the default value will be used.

A crucial rule: Any parameters with default values must be listed after all parameters without default values.

Functions in PHP: Return Values and Parameters

This article from Envato Tuts+ explains how to set default values and, importantly, highlights the correct order for your parameters.

Read the section 'Specifying Default Argument Values'. Pay close attention to the example that causes an error and the explanation for why the order of parameters matters.

Here's a practical example for a web application: a function to create a link. The CSS class is optional.

function createLink($url, $text, $class = 'btn-primary') {
    return "<a href='{$url}' class='{$class}'>{$text}</a>";
}

// Call without the optional class argument
echo createLink('contact.php', 'Contact Us'); 
// Output: <a href='contact.php' class='btn-primary'>Contact Us</a>

// Call and provide a specific class
echo createLink('about.php', 'About', 'btn-secondary');
// Output: <a href='about.php' class='btn-secondary'>About</a>

Type Declarations (Type Hinting)

Modern PHP allows you to specify the expected data type for parameters and for the return value. This makes your code more predictable and helps catch errors early. Your code editor can also use this information to provide better assistance.

// PHP 7+
declare(strict_types=1); // Optional, but recommended for strict enforcement

function calculateTotal(float $price, int $quantity): float {
    return $price * $quantity;
}

$total = calculateTotal(9.99, 3);
echo $total; // Outputs: 29.97

// This would cause a fatal error in strict mode because "hello" is not a float
// $total = calculateTotal("hello", 3); 

The W3Schools page provides a good, concise reference on this topic.

PHP Functions

This article from W3Schools provides a text-based reference for many function concepts, including the modern features of type declarations.

Read the section on 'PHP Return Type Declarations'. The syntax shown (: float) is also applicable to parameter types (float $a).


5. Important Related Concepts

Variable Scope

A variable's "scope" determines where it can be accessed.

  • Local Scope: Variables declared inside a function are local to that function. They cannot be seen or used outside of it.
  • Global Scope: Variables declared outside of any function are global. They cannot be directly accessed inside a function unless you explicitly use the global keyword.

Using the global keyword is generally discouraged in modern professional development because it can make code difficult to trace and debug. It's better to pass values into functions via parameters.

Passing Arguments by Reference

By default, PHP passes arguments "by value." This means the function receives a copy of the variable's value. Any changes made to the parameter inside the function do not affect the original variable outside of it.

However, you can choose to pass an argument "by reference" by adding an ampersand (&) before the parameter name. This means the function gets a direct link to the original variable, and any changes made inside the function will modify the original variable.

This can be useful but should be used with caution as it can have unintended side effects if not managed carefully.

PHP Functions Tutorial - Learn PHP Programming

This final video segment from Clever Techie covers both variable scope and passing by reference, two essential concepts for understanding how functions interact with the rest of your script.

Watch the section on variable scope (10:53 to 12:43) and passing by reference (13:52 to 15:13). For pass-by-reference, notice how the & symbol allows the function to permanently alter the original string variable.


Conclusion

You've now refreshed your understanding of one of the most important concepts in programming. Functions are the building blocks you will use to construct every web application.

Key Takeaways:

  • Functions allow you to package code for reuse, following the DRY principle.
  • You pass data into functions using parameters (the placeholders) and arguments (the actual values).
  • The return statement sends a value back from the function to the calling code.
  • Default parameter values make functions more flexible by making some arguments optional.
  • Type declarations make your code more robust and self-documenting.
  • Variables inside functions have local scope, and passing by reference (&) allows a function to modify an external variable.

In our next lesson, we will dive deeper into working with indexed and associative arrays. You'll see how functions are incredibly powerful tools for processing and manipulating collections of data, which is a common task in web development.