PHP — Functions
Defining a function
Use the function keyword:
<?php
function greet(string $name): string {
return "Hello, $name!";
}
echo greet("Alice"); // Hello, Alice!
?>
PHP functions can have return types (PHP 7+) and parameter types (PHP 7+):
<?php
function add(float $a, float $b): float {
return $a + $b;
}
echo add(3.5, 2.5); // 6
?>
Default parameters
Provide fallback values for parameters:
<?php
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
echo greet("Alice"); // Hello, Alice!
echo greet("Bob", "Hi"); // Hi, Bob!
?>
Default values must be constant expressions — not variables:
<?php
// Valid
function process(string $data, int $limit = 100): string { /* ... */ }
function query(string $sql, string $table = USERS_TABLE): string { /* ... */ }
// Invalid
$x = 5;
function bad(int $n = $x): int { return $n; } // Error
?>
Named arguments
Pass arguments by name instead of position:
<?php
function createUser(string $name, string $email, int $age = 25): void {
echo "$name, $email, age $age\n";
}
// Positional
createUser("Alice", "alice@example.com", 30);
// Named — order doesn't matter
createUser(email: "bob@example.com", name: "Bob", age: 25);
// Mix positional and named (positional must come first)
createUser("Charlie", email: "charlie@example.com");
?>
Variadic functions
Accept any number of arguments with ...:
<?php
function sum(int ...$numbers): int {
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
echo sum(1, 2, 3, 4, 5); // 15
// Or collect remaining arguments
function logMessage(string $level, string ...$messages): void {
foreach ($messages as $msg) {
echo "[$level] $msg\n";
}
}
logMessage("ERROR", "Connection failed", "Retrying...");
// [ERROR] Connection failed
// [ERROR] Retrying...
?>
Return values
Functions can return any type:
<?php
// Return a single value
function isEven(int $n): bool {
return $n % 2 === 0;
}
// Return an array
function divmod(int $a, int $b): array {
return ["quotient" => intdiv($a, $b), "remainder" => $a % $b];
}
$result = divmod(10, 3);
echo $result["quotient"]; // 3
echo $result["remainder"]; // 1
// Return by reference
function &getValue(array &$array, int $index): int {
return $array[$index];
}
$data = [10, 20, 30];
$ref = &$data[1];
$ref = 99;
echo $data[1]; // 99
?>
Type declarations
PHP 7+ supports scalar type declarations:
<?php
function strict(int $n): string {
return (string) $n;
}
// PHP 8.0 union types
function format(int|float $value): string {
return number_format($value, 2);
}
// PHP 8.0 mixed type
function dump(mixed $value): void {
var_dump($value);
}
// PHP 8.1 intersection types
function process(Serializable&Countable $obj): void { /* ... */ }
?>
Anonymous functions (closures)
Functions without a name, assigned to variables:
<?php
$greet = function(string $name): string {
return "Hello, $name!";
};
echo $greet("Alice"); // Hello, Alice!
// Closures can capture outer variables with "use"
$factor = 3;
$multiply = function(int $n) use ($factor): int {
return $n * $factor;
};
echo $multiply(5); // 15
// Capture by reference
$counter = 0;
$increment = function() use (&$counter): void {
$counter++;
};
$increment();
$increment();
echo $counter; // 2
?>
Arrow functions
Short closures (PHP 7.4+):
<?php
$square = fn($x) => $x * $x;
$add = fn($a, $b) => $a + $b;
echo $square(5); // 25
echo $add(3, 4); // 7
// Implicit capture — no "use" keyword needed
$tax = 0.08;
$prices = [100, 200, 300];
$withTax = array_map(fn($p) => $p * (1 + $tax), $prices);
print_r($withTax); // [108, 216, 324]
?>
Built-in functions
PHP has 1000+ built-in functions. Common categories:
<?php
// String
strlen("Hello"); // 5
str_replace("a", "b", "banana"); // "bbnbnb"
substr("Hello", 0, 3); // "Hel"
strtoupper("hello"); // "HELLO"
// Array
count([1, 2, 3]); // 3
array_merge([1, 2], [3, 4]); // [1, 2, 3, 4]
array_filter([1, 2, 3, 4], fn($n) => $n > 2); // [3, 4]
// Math
abs(-5); // 5
max(1, 3, 2); // 3
sqrt(16); // 4
rand(1, 100); // Random int 1-100
// File
file_get_contents("data.txt");
file_put_contents("data.txt", "content");
is_file("data.txt");
?>
Mini Practice
Write PHP code that:
- Defines a function with typed parameters and a return type
- Creates a function with a default parameter value
- Uses an arrow function with
array_map - Demonstrates named arguments when calling a function
Up Next
In the next lesson, you'll learn about Classes — object-oriented programming in PHP.
Related Topics
Frequently Asked Questions about Functions
What is Functions in PHP?
Functions is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Functions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.
Why is Functions important in PHP?
Functions is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.