Skip to content

PHP Functions

Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more modular. PHP provides both built-in functions and the ability to create custom functions.


Functions are declared using the function keyword:

function greet() {
echo "Hello, World!";
}
greet(); // Hello, World!
// Valid function names
function sayHello() { }
function say_hello() { }
function _privateFunction() { }
// Invalid: Cannot start with number or contain hyphens
// function 2sayHello() { }
// function say-hello() { }

Functions can accept parameters to make them more flexible.

function greetUser($name) {
echo "Hello, $name!";
}
greetUser("John"); // Hello, John!
function greetUser($name = "Guest", $greeting = "Hello") {
echo "$greeting, $name!";
}
greetUser(); // Hello, Guest!
greetUser("John", "Hi"); // Hi, John!

By default, functions receive a copy of the variable. Use & to modify the original:

function increment(&$number) {
$number++;
}
$value = 5;
increment($value);
echo $value; // 6

The splat operator (...) collects arguments into an array:

function sumNumbers(...$numbers) {
return array_sum($numbers);
}
echo sumNumbers(1, 2, 3, 4, 5); // 15

Specify arguments by name to skip optional parameters:

function createUser($name, $email, $age = null, $active = true) {
return ['name' => $name, 'email' => $email, 'age' => $age, 'active' => $active];
}
$user = createUser(name: "John", email: "john@example.com", active: false);

Type hints enforce parameter and return types. If you pass a value of the wrong type, PHP throws a TypeError at runtime and the function will not execute.

function createUser(string $name, int $age, bool $active = true): array {
return ['name' => $name, 'age' => $age, 'active' => $active];
}
createUser("John", 25); // Works
createUser("John", "twenty"); // TypeError: Argument #2 must be of type int

Use ? to allow null:

function findUser(?int $id): ?array {
if ($id === null) {
return null;
}
return ['id' => $id, 'name' => 'John'];
}

Accept multiple types:

function process(int|float $number): int|float {
return $number * 2;
}
TypeDescription
string, int, float, boolScalar types
arrayArray type
objectAny object
callableCallable (function/closure)
mixedAny type (PHP 8.0+)
voidNo return value

function multiply($a, $b) {
return $a * $b;
}
echo multiply(4, 5); // 20
function getUserData($id) {
return [
'id' => $id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
}
$user = getUserData(1);
echo $user['name']; // John Doe
function validateAge($age) {
if ($age < 0) {
return "Age cannot be negative";
}
return "Valid age";
}

Static variables retain their value between function calls:

function countCalls() {
static $count = 0;
$count++;
return $count;
}
echo countCalls(); // 1
echo countCalls(); // 2
echo countCalls(); // 3

For more on variable scope (global, local, superglobals), see Variables.