CKTIS / PHP
Pass-by-reference parameter (&$users)
An ampersand before the `$users` parameter lets the function change the caller’s variable without returning the array. At the call site, pass the variable without `&`.
Version: PHP 8.3; extension availability may vary
Syntax
function addUser(array &$users, string $name): void { $users[] = $name; }
$users = ['Ada'];
addUser($users, 'Lin');In array &$users, array specifies the argument type, and the pass-by-reference parameter (&$users) gives the function another name for the caller’s value. Here & is not a pointer or a bitwise AND operator, and the function is not returning a reference.
Call addUser($users, 'Lin'), without &. Pass an initialized variable. A reference returned by a function is also valid, but an array literal is not: addUser(['Ada'], 'Lin') raises an Error. PHP checks the array type on entry, not on return; passing a variable containing a string raises a TypeError.
$users[] = $name appends an element, while an ordinary assignment such as $users = [] would replace the caller’s entire value. The change is still visible after the call, even though the function returns no value (void). Without &, the array is passed by value by default, and the append in this example changes only the local array.
Use & when changing the caller’s variable is intentional, and document that effect because it is not visible at the call site. If the caller should choose whether to replace its array, take it by value and return the modified array instead.
Examples
<?php
function addUser(array &$users, string $name): void
{
$users[] = $name;
}
$users = ['Ada'];
echo implode(', ', $users), "\n";
addUser($users, 'Lin');
echo implode(', ', $users), "\n";
Result
Ada Ada, Lin
The example uses PHP 8.3 CLI and needs no optional extensions. Expect `Ada` before the call and `Ada, Lin` afterward. Remove only `&` from the declaration to see `Ada` on both lines instead.
Related lessons
- PHP · Lesson 28 · Intermediate · Version: 3