Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Array parameter passed by reference: `array &$items`

Declare `array &$items` to require an array when the call begins and let the function modify the caller’s variable without returning a result.

Version: PHP 8.3; extension availability may vary

Syntax

function markReady(array &$items): void { $items[0] = 'ready'; }
$cart = ['draft'];
markReady($cart);

In function markReady(array &$items): void, array declares the input type, $items is the local parameter name, and & means pass by reference. The phrase reference parameter array &$items describes an array-typed parameter that aliases the caller’s variable. Writing to $items[0] or assigning a new value to $items is visible to the caller, even with : void.

Initialize a variable with an array and call markReady($cart). The & belongs in the declaration, not at the call site. Do not pass an array literal such as ['draft'] or an ordinary by-value function result directly; a result returned by reference can be passed. If the supplied variable does not hold an array, PHP throws TypeError on entry. The type is not rechecked on return, so assigning a non-array through $items can even change the type of an ordinary caller variable.

Without &, array $items is passed by value: replacing a plain string element as in the example leaves the caller’s array unchanged. This is not a deep copy: existing references inside the array can still share values. If mutation is not part of the function’s contract, take the array by value and return the result explicitly.

unset($items) removes the local binding, not the caller’s variable. In contrast, foreach ($items as &$item) creates a separate reference to an element. Use unset($item) after such a loop so that a later write to $item cannot overwrite the last visited element.

Examples

<?php
function markReadyCopy(array $items): void
{
    $items[0] = 'ready';
}

function markReady(array &$items): void
{
    $items[0] = 'ready';
}

$cart = ['draft'];
markReadyCopy($cart);
echo $cart[0], "\n";

markReady($cart);
echo $cart[0], "\n";

Result

draft
ready

Both functions write `ready` at index `0`. After the by-value call `$cart[0]` still holds `draft`; after the by-reference call it holds `ready`.

Related lessons

  • PHP · Lesson 19 · Advanced · Version: 2

Sources