How to Restrict PHP Array Types Using PHPDoc

While PHP’s native type system allows you to type-hint parameters and return values as array, it does not natively restrict what types of elements that array can contain. To solve this, developers use PHPDoc docblock annotations. This article demonstrates how to use standard PHPDoc syntax to define expected array element types, enabling IDEs and static analysis tools to catch type mismatches before your code runs.

The most common and widely supported way to restrict array types in PHPDoc is the typed array syntax. By appending square brackets [] to a type, you indicate that the array should only contain elements of that specific type.

/**
 * @param User[] $users An array containing only User objects.
 */
function processUsers(array $users): void {
    foreach ($users as $user) {
        // IDEs know $user is an instance of User
        $user->activate();
    }
}

For more complex structures, static analysis tools like PHPStan and Psalm support generics-style notation. This syntax is highly expressive and allows you to define both the key type and the value type of the array using array<ValueType> or array<KeyType, ValueType>.

/**
 * @var array<string, Product> $inventory
 * An associative array where keys are strings (SKUs) and values are Product objects.
 */
$inventory = [
    'A123' => new Product('Laptop'),
];

You can also specify multiple allowed types within an array using the pipe | operator (union types). For example, (int|string)[] or array<int|string> indicates an array that can contain both integers and strings.

/**
 * @return array<int, string|float>
 */
function getMetrics(): array {
    return [10.5, "Success", 99];
}

By consistently using these PHPDoc annotations on your @param, @return, and @var tags, modern IDEs and static analyzers will highlight code that attempts to insert invalid types into your arrays, bringing strict type safety to PHP collections.