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:
<?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.
*/
function outputOptions()
{
global $options;
foreach ($options as $option) {
echo $option . "\n";
}
}
outputOptions();
?>
Watch a video course
Learn object oriented PHP
You can also specify the type of elements the array contains by using the []
notation after the type, like this:
<?php
/**
* @var array[int] $numbers An array of integers.
*/
$numbers = [1, 2, 3, 4, 5];
/**
* Function to output the contents of the $numbers array.
*/
function outputNumbers()
{
global $numbers;
foreach ($numbers as $number) {
echo $number . "\n";
}
}
outputNumbers();
?>
It's also a good practice to document the keys of the array if they're important, like this:
<?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.
*/
function outputScores()
{
global $scores;
foreach ($scores as $player => $score) {
echo $player . ": " . $score . "\n";
}
}
outputScores();
?>
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.