Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Pass-by-reference parameter (`&$list`)

Putting `&` before `$list` lets a PHP function change the caller's variable. Write it in the parameter declaration, not next to the argument at the call site.

Version: PHP 8.3

Syntax

<?php
function appendItem(array &$list, string $item): void
{
    $list[] = $item;
}

$items = ['apple'];
appendItem($items, 'pear');

In PHP 8.3, a pass-by-reference parameter (&$list) lets the function work on the caller's variable. In appendItem($items, 'pear'), the local name $list becomes an alias for the same contents as $items. A PHP reference is not a memory-address pointer. $list is an ordinary parameter name, unrelated to the list() destructuring construct.

The reference syntax, array operations, and implode() used in the example do not require any optional PHP extensions.

Put & before the parameter name in the declaration, not before the argument in the call. Pass a variable such as $items; passing a literal like ['apple'] to the reference parameter is an error. A result returned by reference is also valid. Accepting an argument by reference does not mean returning by reference.

$list[] = $item appends to the caller's array, and $list = [] would replace it entirely. Those changes remain visible after the call. In contrast, unset($list) inside the function only removes the local binding, not $items. Without &, the default is pass-by-value, so the append shown here would leave $items unchanged.

In array &$list, PHP checks the array type on entry, not on return: passing a variable that contains an integer raises a TypeError. void describes the return value, not the change to the argument. Use references when changing the caller's variable is intentional, and document that side effect because it is not visible at the call site.

Examples

<?php
function appendItem(array &$list, string $item): void
{
    $list[] = $item;
}

$items = ['apple'];
appendItem($items, 'pear');
echo implode(', ', $items), "\n";

Result

apple, pear

After calling `appendItem()`, the script prints `$items`, not a function return value. The expected line is `apple, pear`. Remove only `&` from the parameter declaration to compare: the expected line is then `apple`.

Related lessons

  • PHP · Lesson 20 · Intermediate · Version: 3

Sources