Skip to main content
PHP for Beginners
CHAPTER 09 Beginner

PHP Functions

Updated: May 12, 2026
20 min read

# Chapter 9: PHP Functions

1. Introduction

Welcome to Chapter 9! As your web applications grow, you'll find yourself writing the same code over and over. For example, validating an email address or connecting to a database. Copying and pasting code is a terrible practice—it makes your files huge and a nightmare to update. This is where Functions come in. A function is a reusable block of code that performs a specific task. In this chapter, we will learn how to create our own custom functions, pass data into them, and get results back.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare and call custom PHP functions.
  • Pass data into functions using Parameters/Arguments.
  • Return calculated data from a function using the return keyword.
  • Set default values for parameters.
  • Understand variable scope inside and outside functions.

3. Function Creation and Calling

To create a function, use the function keyword, followed by a name, parentheses (), and curly braces {} containing the code. To execute the function, you "call" it by writing its name followed by parentheses.
php
12345678910
<?php
// 1. Defining the function
function sayHello() {
    echo "Hello, welcome to my website! <br>";
}

// 2. Calling the function
sayHello();
sayHello(); // We can call it as many times as we want!
?>

4. Function Parameters (Arguments)

Information can be passed to functions through arguments (variables inside the parentheses). This makes functions dynamic and adaptable.
php
123456789
<?php
// The function expects a $name parameter
function greetUser($name) {
    echo "Hello, $name! <br>";
}

greetUser("Alice");
greetUser("Bob");
?>

5. Return Values

Instead of just echoing data directly to the screen, a well-designed function usually performs a calculation and returns the result back to the main script. Use the return keyword for this. Once a function hits a return statement, it stops executing immediately.
php
12345678910
<?php
function addNumbers($a, $b) {
    $sum = $a + $b;
    return $sum; // Sends the result back
}

// Storing the returned value in a variable
$total = addNumbers(5, 10);
echo "The total is: " . $total;
?>

6. Default Parameters

You can set a default value for a parameter. If the user calls the function without passing an argument, the default value is used.
php
123456789
<?php
// $color defaults to "Red" if nothing is provided
function setBackgroundColor($color = "Red") {
    echo "The background is now $color. <br>";
}

setBackgroundColor("Blue"); // Uses "Blue"
setBackgroundColor();       // Uses default "Red"
?>

7. Variable Scope

Variables declared *outside* a function cannot be accessed *inside* the function. Variables declared *inside* a function cannot be accessed *outside*. This is called Variable Scope. It prevents your variables from accidentally overwriting each other.
php
12345678910111213
<?php
$my_name = "Global John";

function tryToPrintName() {
    // This will cause an error! $my_name is not defined inside this function.
    // echo $my_name; 
    
    $local_name = "Local Jane"; // Only exists inside this function
}

// This will also cause an error! $local_name doesn't exist out here.
// echo $local_name;
?>

8. Real-World Examples

Imagine you need to format prices across an entire e-commerce site. Instead of repeating the formatting code, create a function.
php
12345678910
<?php
function formatPrice($price) {
    // number_format is a built-in PHP function
    $formatted = number_format($price, 2); 
    return "$" . $formatted;
}

$cart_total = 199.5;
echo "Total Due: " . formatPrice($cart_total); // Outputs: Total Due: $199.50
?>

9. Output Explanations

In the pricing example, we pass 199.5 into formatPrice(). The function uses a built-in PHP function number_format() to ensure there are exactly two decimal places (199.50), concatenates a dollar sign, and returns the string "$199.50". The main script then echoes the returned string.

10. Common Mistakes

  • Forgetting the return statement: If your function calculates a total but forgets to return it, calling the function will result in NULL.
  • Calling a function before it exists? Actually, PHP is smart! You can call a function at the top of the file even if it is defined at the bottom. But you cannot call a function that is misspelled.
  • Missing Required Arguments: If a function expects 2 parameters and has no defaults, calling it with only 1 parameter will trigger a fatal error.

11. Best Practices

  • Do One Thing: A function should do exactly ONE specific task. Don't write a processUser() function that validates, saves to the database, sends an email, and echoes HTML. Break those into 4 separate functions!
  • Naming Conventions: Use clear, action-oriented verbs. calculateTotal(), getUser(), sendEmail().
  • Return, don't Echo: Functions should generally return data so the main script can decide whether to echo it, save it, or pass it to another function.

12. Exercises

  1. 1. Create a function called multiply() that takes two numbers, multiplies them, and returns the result.
  1. 2. Call your function, store the result in a variable, and echo it.
  1. 3. Create a function with a default parameter for a user's role (defaulting to "Guest").

13. Mini Project: BMI Calculator

Task: Build a reusable function to calculate a Body Mass Index (BMI) and another function to determine the health category.
php
1234567891011121314151617181920212223242526272829303132
<?php
// Function to calculate BMI
function calculateBMI($weight_kg, $height_m) {
    $bmi = $weight_kg / ($height_m * $height_m);
    return round($bmi, 1); // round() is a built-in function to 1 decimal
}

// Function to get category
function getBMICategory($bmi) {
    if ($bmi < 18.5) return "Underweight";
    if ($bmi < 25) return "Normal weight";
    if ($bmi < 30) return "Overweight";
    return "Obese";
}

// Using the functions
$user_weight = 70; // 70kg
$user_height = 1.75; // 1.75m

$user_bmi = calculateBMI($user_weight, $user_height);
$user_category = getBMICategory($user_bmi);
?>

<!DOCTYPE html>
<html>
<head><title>BMI Tool</title></head>
<body>
    <h2>Your Health Report</h2>
    <p>BMI Score: <strong><?php echo $user_bmi; ?></strong></p>
    <p>Category: <strong><?php echo $user_category; ?></strong></p>
</body>
</html>

14. Coding Challenges

Challenge 1: Write a function called isAdult($age) that returns boolean true if the age is 18 or older, and false if it is not. Test it with an if statement.
php
123456789101112
<?php
// Solution
function isAdult($age) {
    return $age >= 18;
}

if (isAdult(20)) {
    echo "Welcome to the adult section.";
} else {
    echo "You are too young.";
}
?>

15. MCQs with Answers

1. Which keyword is used to send data back from a function? A) echo B) send C) return D) export *Answer: C*

2. Can a function access a variable that was declared outside of it (by default)? A) Yes, all variables are global. B) No, due to variable scope constraints. C) Only if the variable is a string. D) Only if the function uses a while loop. *Answer: B*

3. What happens if a function is called without an argument for a parameter that has a default value? A) A fatal error occurs. B) The script ignores the function. C) The parameter becomes NULL. D) The default value is used. *Answer: D*

16. Interview Questions

Q: Explain Variable Scope in PHP. *A:* Scope refers to the context in which a variable is defined and can be accessed. In PHP, variables defined outside a function have Global scope and cannot be accessed inside functions. Variables defined inside a function have Local scope and cannot be accessed outside. You can pass data into a function via arguments to cross this boundary.

Q: Why is it better for a function to return a value rather than echo it directly? *A:* Reusability. If a function echoes output directly, you can never use that function to just calculate a value quietly in the background or save it to a database—it will always forcefully print to the screen. Returning the value gives the caller full control over what to do with the data.

17. FAQs

Q: Are there built-in functions in PHP? *A:* Yes! Thousands of them. echo, print, vardump, numberformat, and round are all built-in functions. You are just learning how to create your own!

18. Summary

Functions are the building blocks of clean, organized applications. You learned how to define functions, pass dynamic data to them via parameters, set default parameters, and safely return results using the return keyword. You also grasped the critical concept of variable scope.

19. Next Chapter Recommendation

Currently, a variable can only hold one single piece of data. But what if we have a list of 100 users? Creating 100 variables ($user1, $user2) is impossible. In Chapter 10: PHP Arrays, we will learn how to store lists and complex data structures inside a single powerful variable!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·