Function Arguments
What Are Function Arguments? In simple terms: Arguments are the values you give a function when you call it, so it can work with different data each time. Technically: A function declares parameters —
What Are Function Arguments?
In simple terms: Arguments are the values you give a function when you call it, so it can work with different data each time.
Technically: A function declares parameters — variables listed in its definition. When the function is called, each argument is assigned to the corresponding parameter. Inside the function, parameters behave like local variables.
function greet(string $name) // $name is a parameter
{
return "Hello, $name";
}
greet("Asha"); // "Asha" is an argument
Why Arguments Matter
Without arguments, a function could only ever do exactly the same thing. Arguments make functions general: one calculateTax() function can handle any amount, and one sendEmail() function can send any message to anyone.
Positional Arguments
By default, arguments are matched to parameters by position: the first argument goes to the first parameter, the second to the second, and so on.
Example
<?php
function fullName(string $first, string $last): string
{
return "$first $last";
}
echo fullName('Priya', 'Sharma') . "\n";
echo fullName('Sharma', 'Priya') . "\n";
Output
Priya Sharma
Sharma Priya
The second call passes the same values in a different order, and the result changes. With positional arguments, order matters — PHP cannot tell that you swapped them, because both are strings.
For functions with many parameters or several of the same type, named arguments (PHP 8.0+) make calls unambiguous: fullName(last: 'Sharma', first: 'Priya'). See Named Arguments.
Passing Expressions
Any expression can be an argument. It is evaluated before the function is called, and its result is passed:
<?php
function percentage(float $part, float $whole): float
{
return round($part / $whole * 100, 1);
}
$correct = 37;
$questions = 40;
echo percentage($correct, $questions) . "%\n";
echo percentage($correct + 2, $questions) . "%\n";
echo percentage(count(['a', 'b', 'c']), 4) . "%\n";
Output
92.5%
97.5%
75%
- Variables, calculations (
$correct + 2), and even other function calls (count([...])) can be passed. - Arguments are evaluated from left to right.
Wrong Number of Arguments
Too Few Arguments
<?php
function fullName(string $first, string $last): string
{
return "$first $last";
}
try {
echo fullName('Priya');
} catch (ArgumentCountError $e) {
echo $e->getMessage() . "\n";
}
Output
Too few arguments to function fullName(), 1 passed in /path/script.php on line 8 and exactly 2 expected
Calling a function without all required parameters throws an ArgumentCountError. The message tells you which function, how many arguments were passed, and where the call is. To make a parameter optional, give it a default value (see Default Argument Values).
Too Many Arguments
<?php
function fullName(string $first, string $last): string
{
return "$first $last";
}
echo fullName('Priya', 'Sharma', 'extra value') . "\n";
try {
echo strlen('abc', 'extra');
} catch (ArgumentCountError $e) {
echo $e->getMessage() . "\n";
}
Output
Priya Sharma
strlen() expects exactly 1 argument, 2 given
- User-defined functions silently ignore extra arguments. They can still be read with
func_get_args(), but this is a legacy technique; use variadic parameters instead (see Variadic Functions). - Built-in functions are strict and throw an
ArgumentCountErrorfor extra arguments.
Silently ignored arguments can hide bugs — for example, when a caller passes an argument that the function was supposed to use but does not. Static analysis tools such as PHPStan report these calls.
Arguments Are Passed by Value
By default, PHP passes a copy of each argument's value. Changing the parameter inside the function does not affect the caller's variable.
Example
<?php
function addBonus(array $scores, int $bonus): array
{
foreach ($scores as $name => $score) {
$scores[$name] = $score + $bonus;
}
return $scores;
}
$original = ['Asha' => 70, 'Bala' => 85];
$withBonus = addBonus($original, 5);
print_r($original);
print_r($withBonus);
Output
Array
(
[Asha] => 70
[Bala] => 85
)
Array
(
[Asha] => 75
[Bala] => 90
)
Why This Is Useful
- The function cannot accidentally change the caller's data.
- The result is returned explicitly, so the caller decides whether to use it, store it, or replace the original (
$scores = addBonus($scores, 5);).
Copying is cheap: PHP uses copy-on-write, so an array is duplicated only if the function actually modifies it. Passing large arrays to functions is not a performance problem.
To let a function modify the caller's variable directly, use pass by reference (&) — see Pass by Reference.
Objects Behave Differently
Objects are passed as handles (identifiers pointing to the same object). The handle is copied, but both copies refer to the same object, so changes to its properties are visible to the caller:
<?php
function markAsShipped(stdClass $order): void
{
$order->status = 'shipped';
}
$order = new stdClass();
$order->id = 4021;
$order->status = 'paid';
markAsShipped($order);
echo "Order {$order->id} is now {$order->status}\n";
Output
Order 4021 is now shipped
No & is needed. If a function must not change an object, either pass a clone, or design the object to be immutable (for example, using readonly properties, covered in Readonly Properties). DateTimeImmutable is a built-in example of an immutable object.
Type Declarations on Parameters
Parameter types state what each argument must be. PHP checks every argument when the function is called:
<?php
function repeatText(string $text, int $times): string
{
return str_repeat($text, $times);
}
echo repeatText('ab', '3') . "\n";
try {
echo repeatText('ab', 'three');
} catch (TypeError $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
Output
ababab
TypeError: repeatText(): Argument #2 ($times) must be of type int, string given, called in /path/script.php on line 10
- In the default (coercive) mode, the numeric string
'3'is converted to the integer3. 'three'cannot become an integer, so PHP throws aTypeErrorthat names the function, the argument number, the parameter, and the line of the call.- With
declare(strict_types=1);, even'3'would be rejected.
Types are covered in Type Declarations in Functions and Strict Types.
Designing Good Parameter Lists
Order Parameters by Importance
Put the essential, required parameters first and optional ones last:
function sendEmail(string $to, string $subject, string $body, bool $isHtml = false) { ... }
Keep the Number of Parameters Small
Long parameter lists are hard to call correctly:
createUser('Asha', 'asha@example.com', 'editor', true, false, 'Chennai', null, 'ta');
What do true, false, and null mean here? Better options:
- Named arguments:
createUser('Asha', 'asha@example.com', role: 'editor', active: true). - An options array for many optional settings.
- An object (data transfer object) that groups related values, such as an
AddressorNewUserobject.
Avoid Boolean Flags That Change Behavior
render($data, true) gives no hint what true means. Separate functions (renderHtml(), renderJson()), a named argument, or an enum is clearer.
Trailing Commas
PHP allows a trailing comma after the last argument (PHP 7.3+) and after the last parameter in a definition (PHP 8.0+). This makes multi-line calls and definitions easier to edit:
<?php
function createInvoice(
string $customer,
float $amount,
string $currency,
): string {
return sprintf('%s: %s %.2f', $customer, $currency, $amount);
}
echo createInvoice(
'Lakshmi Traders',
12500,
'INR',
);
Output
Lakshmi Traders: INR 12500.00
Adding a new parameter later changes only one line, which also produces cleaner diffs in version control.
Common Mistakes
Passing Arguments in the Wrong Order
Effect: Values end up in the wrong parameters, often without any error when types match.
Fix: Check the signature; use named arguments for functions with several parameters of the same type.
Expecting a Function to Change the Caller's Variable
Effect: Changes inside the function are lost because the array or scalar was copied.
Fix: Return the new value and assign it, or (when justified) use pass by reference.
Relying on Ignored Extra Arguments
Effect: Values you think are being used are silently discarded.
Fix: Pass exactly the declared arguments; use variadic parameters when a function should accept any number.
Long Lists of Unlabeled Arguments
Effect: Calls like f(true, false, null, 3) are unreadable and error-prone.
Fix: Reduce parameters, use named arguments, or group values into an array or object.
Best Practices
- Keep parameter lists short, with required parameters first.
- Declare a type for every parameter.
- Rely on pass-by-value and return results instead of modifying inputs.
- Use named arguments for clarity when calling functions with several optional or same-typed parameters.
- Use trailing commas in multi-line parameter and argument lists.
Official reference: https://www.php.net/manual/en/functions.arguments.php