← Back to PHP Course | Chapter 5: Functions | Lesson 2 of 10

PHP Function Parameters

What are Parameters?

Parameters are the named placeholders listed inside a function's parentheses when you define it. When you later *call* the function, the arguments you supply fill those placeholders in order, giving the function's body something concrete to work with.

Example: What are Parameters?

php
<?php
function greet($name) {
    echo "Hello, $name!";
}
greet("Alice");
?>

Pass by Value

By default, PHP copies an argument's value into the function — any changes made to the parameter inside the function body stay local and never touch the original variable back where the function was called. This is why plain function calls can't accidentally mutate a variable you pass in.

Example: Pass by Value

php
<?php
function addOne($num) {
    $num = $num + 1;
    echo "Inside: $num\n";
}
$x = 5;
addOne($x);
echo "Outside: $x";
?>

Pass by Reference

Prefixing a parameter name with & in the function definition switches it to pass-by-reference: the function now operates on the original variable itself, so any change it makes is visible back at the call site once the function returns — the opposite of the default copy behavior.

Example: Pass by Reference

php
<?php
function addOne(&$num) {
    $num = $num + 1;
}
$x = 5;
addOne($x);
echo $x;
?>

Typed Parameters

Adding a type declaration before a parameter name (function greet(string $name)) tells PHP to enforce that type at the call site. Pass something that doesn't match — an array where a string was expected — and PHP throws a TypeError immediately, rather than silently coercing or misbehaving later.

Example: Typed Parameters

php
<?php
function greet(string $name) {
    echo "Hello, $name!";
}
greet("Alice");
?>

Variadic Parameters (... operator)

The ... operator before a parameter name collects any number of extra arguments into a single array inside the function, letting you write one function that accepts a flexible, unknown-in-advance number of values rather than a fixed parameter list.

Example: Variadic Parameters (... operator)

php
<?php
function sumAll(...$numbers) {
    return array_sum($numbers);
}
echo sumAll(1, 2, 3, 4);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.