Functions in PHP
What is a Function?
A function is a reusable block of code that performs a specific task, which you can call by name whenever you need it, instead of rewriting the same logic over and over. Functions are one of the most important tools for keeping code organized, readable, and maintainable — rather than one long script from top to bottom, you break your logic into smaller, named pieces that each do one clear thing.
If you've ever used echo, strlen(), or count(), you've already been using PHP's built-in functions. This lesson focuses on creating your own.
Defining a Basic Function
Functions are defined using the function keyword, followed by a name and parentheses.
php
<?php
function sayHello() {
echo "Hello, welcome to MasterPHP!";
}
sayHello(); // calling the function runs its code
Nothing inside a function runs until it's actually called by name. You can define a function once and call it as many times as needed throughout your script.
Function Parameters
Functions become far more useful when they can accept input, called parameters, which let the same function behave differently depending on what's passed in.
php
<?php
function greetUser($name) {
echo "Hello, $name!";
}
greetUser("Rohan"); // Hello, Rohan!
greetUser("Priya"); // Hello, Priya!
A function can accept multiple parameters, separated by commas:
php
<?php
function calculateTotal($price, $quantity) {
echo $price * $quantity;
}
calculateTotal(250, 3); // 750
Default Parameter Values
PHP allows parameters to have a default value, used automatically if the caller doesn't provide one.
php
<?php
function greetUser($name = "Guest") {
echo "Hello, $name!";
}
greetUser("Rohan"); // Hello, Rohan!
greetUser(); // Hello, Guest!
Default values are especially useful for optional settings or configuration-style parameters, where most calls will use the same common value but occasionally need to be overridden.
Return Values
Instead of directly printing output with echo, functions can send a value back to wherever they were called using return. This is generally the more flexible and reusable approach.
php
<?php
function addNumbers($a, $b) {
return $a + $b;
}
$sum = addNumbers(10, 5);
echo $sum; // 15
// The returned value can be used directly too
echo addNumbers(20, 30); // 50
The key difference between echo and return is important: echo immediately outputs text to the browser, while return sends a value back into your code so it can be stored, reused, or passed into another function. As a general rule, functions that calculate or process data should use return, keeping the decision of what to do with that value (display it, save it, pass it along) up to the calling code.
Approach What it does Reusable?
------------------------------------------------------------
echo Outputs directly to the browser No - locked to
display only
return Sends a value back to the caller Yes - can be
stored, reused,
or passed on
Once a return statement executes, the function stops immediately — any code written after it inside that function will never run.
php
<?php
function checkAge($age) {
if ($age < 18) {
return "Minor";
}
return "Adult";
echo "This line never runs"; // unreachable code
}
echo checkAge(15); // Minor
Type Hints and Return Types
Modern PHP allows you to specify what type of data a function expects and what type it will return, which helps catch mistakes early and makes function behavior more predictable.
php
<?php
function calculateTotal(int $price, int $quantity): int {
return $price * $quantity;
}
echo calculateTotal(250, 3); // 750
// echo calculateTotal("abc", 3); // triggers a TypeError
Adding int before each parameter name enforces that only integers are accepted, and the : int after the parentheses declares that the function will return an integer. This is called strict typing context, and while PHP doesn't require it, using type hints is considered a modern best practice — it makes functions self-documenting and catches type-related bugs immediately rather than letting them silently cause unexpected behavior later.
Nullable and Union Types
Sometimes a parameter or return value might legitimately be more than one type, or might be absent entirely. PHP supports this with nullable and union type syntax:
php
<?php
function findUser(?string $username): string|null {
if ($username === null) {
return null;
}
return "User: $username";
}
echo findUser("Rohan"); // User: Rohan
echo findUser(null); // (returns null, nothing printed)
The ?string means the parameter accepts either a string or null, while string|null as a return type explicitly states the function can return either type.
Variable Scope Inside Functions
As covered in the previous lesson, variables created inside a function are local to that function by default. Parameters follow this same rule, existing only within the function they belong to.
php
<?php
function double($number) {
$number = $number * 2;
return $number;
}
$original = 10;
$doubled = double($original);
echo $original; // 10 - unchanged
echo $doubled; // 20
Arrow Functions (Short Closures)
PHP 7.4 introduced arrow functions, a more concise syntax for simple, single-expression functions — commonly used with array functions like array_map() or usort().
php
<?php
$numbers = [1, 2, 3, 4, 5];
// Traditional anonymous function
$doubled = array_map(function ($n) {
return $n * 2;
}, $numbers);
// Equivalent arrow function - shorter, and automatically captures $variables from outside
$multiplier = 2;
$doubled = array_map(fn($n) => $n * $multiplier, $numbers);
print_r($doubled); // [2, 4, 6, 8, 10]
Arrow functions automatically inherit variables from the surrounding scope (like $multiplier above) without needing the use keyword that traditional anonymous functions require — making them noticeably cleaner for short, simple operations.
Variadic Functions: Accepting Any Number of Arguments
Occasionally you won't know in advance how many arguments a function should accept. PHP handles this with the ... (spread) syntax:
php
<?php
function sumAll(...$numbers) {
return array_sum($numbers);
}
echo sumAll(1, 2, 3); // 6
echo sumAll(10, 20, 30, 40); // 100
Inside the function, $numbers automatically becomes an array containing whatever values were passed in, regardless of how many there were.
Naming Functions Well
Function names should clearly describe what the function does, typically using a verb since a function performs an action.
Good Function Name Poor Function Name ------------------------------------------------------------ calculateTotal() doStuff() sendWelcomeEmail() process() isValidEmail() check()
Clear naming becomes increasingly valuable as a project grows, since well-named functions make code readable almost like plain English, without needing to dig into the implementation to understand what's happening.
What's Next
With functions under your belt, the next essential building block is loops — which let you repeat actions efficiently, whether that's processing every item in an array, validating multiple form fields, or generating repeated HTML output.