Custom Functions

Learn to create reusable code blocks with custom functions.

Functions

Functions let you write code once and reuse it many times. They are the building blocks of modular, maintainable code.

Basic Functions

PHP Functions
<?php
// Simple function
function greet() {
    echo "Hello, World!";
}
greet();  // Call the function

// Function with parameter
function greetUser($name) {
    echo "Hello, $name!";
}
greetUser("John");  // Hello, John!

// Function with return value
function add($a, $b) {
    return $a + $b;
}
$result = add(5, 3);  // 8

// Multiple parameters
function calculateArea($width, $height) {
    return $width * $height;
}
$area = calculateArea(5, 10);  // 50
?>

Default Parameters

PHP Default Values
<?php
// Default parameter value
function welcome($name = "Guest") {
    echo "Welcome, $name";
}
welcome();        // Welcome, Guest
welcome("Anna");  // Welcome, Anna

// Multiple defaults
function createUser($name, $role = "user", $active = true) {
    return [
        "name" => $name,
        "role" => $role,
        "active" => $active
    ];
}

// Named arguments (PHP 8+)
createUser(name: "John", active: false);
?>

Pro Tip: Required parameters should come before optional ones. PHP doesn't check parameter names, so positional order matters.

Pass by Reference

PHP References
<?php
// Pass by value (default)
function addFive($num) {
    $num += 5;
}
$value = 10;
addFive($value);
echo $value;  // 10 (unchanged)

// Pass by reference
function addFiveRef(&$num) {
    $num += 5;
}
$value = 10;
addFiveRef($value);
echo $value;  // 15 (changed!)

// Reference with arrays
function addItem(&$array, $item) {
    $array[] = $item;
}
$colors = ["Red"];
addItem($colors, "Green");
print_r($colors);  // ["Red", "Green"]
?>

Returning Values

PHP Return
<?php
// Return single value
function multiply($a, $b) {
    return $a * $b;
}

// Return multiple values (array)
function getStats($numbers) {
    return [
        "sum" => array_sum($numbers),
        "average" => array_sum($numbers) / count($numbers),
        "min" => min($numbers),
        "max" => max($numbers)
    ];
}
$stats = getStats([10, 20, 30]);
echo $stats["sum"];  // 60

// Early return
function divide($a, $b) {
    if ($b == 0) {
        return "Cannot divide by zero";
    }
    return $a / $b;
}

// Return type declaration (PHP 7+)
function add(int $a, int $b): int {
    return $a + $b;
}
?>

Anonymous Functions

PHP Closures
<?php
// Anonymous function
$greet = function($name) {
    return "Hello, $name";
};
echo $greet("World");

// With array functions
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
$evens = array_filter($numbers, fn($n) => $n % 2 == 0);

// Closure with use
$multiplier = 10;
$calc = function($n) use ($multiplier) {
    return $n * $multiplier;
};
?>

Hands-on Exercises

Exercise 1: Create a function that checks if a number is prime
Exercise 2: Create a function that reverses a string
Exercise 3: Create a function that calculates factorial (n!)
Exercise 4: Create a function that finds the largest of 3 numbers
Exercise 5: Use array_map() with an anonymous function to convert temperatures