Function Arguments

Pass information into a function through arguments.

Syntaxfunction name(type $arg1, type $arg2) { ... }

Arguments let you pass data into a function. They are listed inside the parentheses of the definition and act like local variables.

You can add type declarations before each argument to enforce the expected type.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Accept a user ID and a permission string as arguments in an isAllowed() function used across the auth layer.
  • Pass an array of order line items into a calculateSubtotal() function that sums them and returns the total.
  • Pass a database connection handle as an argument to a query helper so it can be tested with a mock connection.

More examples

Multiple typed arguments

Type-hinted arguments enforce the expected types; multiple parameters let callers customise behaviour.

Example · php
<?php
function createSlug(string $title, string $separator = '-'): string {
    return strtolower(str_replace(' ', $separator, trim($title)));
}

echo createSlug('Hello World');       // hello-world
echo createSlug('Hello World', '_');  // hello_world

Variadic arguments with ...

The ... spread operator collects any number of arguments into an array, enabling variadic functions.

Example · php
<?php
function sumAll(float ...$numbers): float {
    return array_sum($numbers);
}

echo sumAll(1.5, 2.5, 3.0, 4.0); // 11.0

Passing arguments by reference

Passing by reference with & lets the function modify the caller's variable directly instead of a copy.

Example · php
<?php
function normalise(string &$str): void {
    $str = strtolower(trim($str));
}

$input = '  Hello World  ';
normalise($input);
echo $input; // hello world

Discussion

  • Be the first to comment on this lesson.