Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

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

`array &$product` requires an array at the call and lets the function change the caller’s variable without returning the array.

Version: PHP 8.3; extension availability may vary

Syntax

function restock(array &$product): void { $product['stock'] += 2; }
// Call with an array variable containing a numeric 'stock' value, without &:
$item = ['stock' => 3];
restock($item);

In function restock(array &$product): void, array declares the input type, & means pass by reference, and $product is the local parameter name. The reference applies to the variable holding the whole array; it does not turn the array’s elements into references.

Before calling restock($item), assign $item an array with a numeric value under the stock key, such as ['stock' => 3]. Put & in the declaration, not at the call site. An array literal is not a valid argument for this parameter, although a function that returns an array by reference can supply one.

$product and $item refer to the same value. The function can update an element or replace the whole array, and the change is still visible after the call. : void means there is no return value, not that there are no side effects. Without &, the parameter is passed by value and the same update to an ordinary element stays local; elements that are already references can still be shared.

PHP checks array on entry and throws a TypeError if the supplied variable does not hold an array. It does not check keys or element types, or recheck the parameter type on return. An empty array therefore passes the type check, but in PHP 8.3, += emits a warning when it reads the missing stock key. When modifying an ordinary variable, leave it holding an array if callers expect it to remain one.

Examples

<?php

function restock(array &$product): void
{
    $product['stock'] += 2;
}

$item = ['stock' => 3];
echo $item['stock'], "\n";
restock($item);
echo $item['stock'], "\n";

Result

3
5

The output is `3` followed by `5`. The function adds `2` to `$product['stock']`, so `$item['stock']` is `5` after the call even though the function returns no value.

Related lessons

  • PHP · Lesson 20 · Advanced · Version: 2

Sources