Skip to content

Best way to document Array options in PHPDoc?

When documenting an array option in PHPDoc, you can use the @var tag followed by the type array and a short description of the option. For example:

Example of documenting an array option in PHPDoc

php
<?php
/**
 * @var array<string> $options An array of strings as options for the function.
 */

$options = ["Option 1", "Option 2", "Option 3"];

/**
 * Function to output the contents of the $options array.
 *
 * @param array<string> $options An array of strings to output.
 * @return void
 */
function outputOptions(array $options): void
{
  foreach ($options as $option) {
    echo $option . "\n";
  }
}

outputOptions($options);
?>

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

You can also specify the type of elements the array contains using the array<type> syntax, like this:

Documenting array element types in PHPDoc

php
<?php
/**
 * @var array<int> $numbers An array of integers.
 */

$numbers = [1, 2, 3, 4, 5];

/**
 * Function to output the contents of the $numbers array.
 *
 * @param array<int> $numbers An array of integers to output.
 * @return void
 */
function outputNumbers(array $numbers): void
{
  foreach ($numbers as $number) {
    echo $number . "\n";
  }
}

outputNumbers($numbers);
?>

It's also a good practice to document the keys of the array if they're important, like this:

Documenting associative array keys and values

php
<?php
/**
 * @var array<string, int> $scores An associative array of strings (player names) as keys and integers (scores) as values.
 */

$scores = array("Player 1" => 100, "Player 2" => 200, "Player 3" => 300);

/**
 * Function to output the contents of the $scores array.
 *
 * @param array<string, int> $scores An associative array of player names and scores.
 * @return void
 */
function outputScores(array $scores): void
{
  foreach ($scores as $player => $score) {
    echo $player . ": " . $score . "\n";
  }
}

outputScores($scores);
?>

Overall, it's important to be as descriptive and clear as possible when documenting an array option, so that other developers can understand how to use it correctly.

Dual-run preview — compare with live Symfony routes.