Eduardo Arsand

PHP Typed Arrays

258

PHP's native type declarations let you require an array, but they cannot describe its keys or values.

PHPDoc annotations can fill this gap. Static analyzers interpret them to check whether code matches the documented types.

This note catalogs the array typing patterns I extracted from PHPStan documentation and practical implementation.

Each pattern addresses a different structure: arrays with a consistent value type, sequential lists, fixed shapes, or additional constraints.

The snippets focus on the type annotations. Supporting classes and persistence details are omitted where they are not shown.

Basic Array Type Notation

The foundational syntax takes three forms: Type[], array<Type>, and array<KeyType, ValueType>.

Type[] and array<Type> specify the value type. Use array<KeyType, ValueType> when you also need to specify the key type.

<?php
    /**
     * @param User[] $users
     * @return array<string>
     */
    function extractNames(array $users): array {
        return array_map(fn($u) => $u->getName(), $users);
    }

    /**
     * @param array<string, int> $scores
     */
    function calculateAverage(array $scores): float {
        return array_sum($scores) / count($scores);
    }
?>

Lists: Sequential Integer Keys

Lists are arrays whose integer keys start at 0 and increase by 1. That distinction matters when encoding an array as JSON: keys that are not a continuous sequence from 0 produce a JSON object instead of a JSON array. PHP's json_encode() documentation describes this behavior.

<?php
    /**
     * @param list<int> $numbers
     * @return non-empty-list<int>
     */
    function ensureNonEmpty(array $numbers): array {
        return $numbers ?: [0];
    }
?>

Array Shapes: Structured Data

Array shapes describe the expected keys and value types for a structured array. A static analyzer can check code against that shape.

I use them extensively for configuration arrays, API responses, and database row structures.

<?php
    /**
     * @param array{name: string, age: int, email?: string} $user
     * @param int $id
     * @return array{id: int, name: string, created_at: string}
     */
    function createUserData(array $user, int $id): array {
        return [
            'id' => $id,
            'name' => $user['name'],
            'created_at' => date('Y-m-d H:i:s')
        ];
    }
?>

Managing Complex Array Shapes

Array shapes can become difficult to read when they exceed a line's readable length.

Inline documentation with 10 or more keys can become hard to maintain. Break it into several lines.

<?php
    /**
     * @param array{
     *     id: int,
     *     name: string,
     *     email: string,
     *     phone?: string,
     *     address: array{street: string, city: string, zip: string},
     *     preferences: array{notifications: bool, theme: string},
     *     metadata: array<string, mixed>
     * } $data
     */
    function saveUser(array $data): void {
        //Persistence is omitted from this example.
    }
?>

Local type aliases can keep complex shapes from being repeated across a class. PHPStan provides the @phpstan-type annotation for this.

<?php
    /**
     * @phpstan-type UserData array{
     *     id: int,
     *     name: string,
     *     email: string,
     *     phone?: string,
     *     address: array{street: string, city: string, zip: string},
     *     preferences: array{notifications: bool, theme: string},
     *     metadata: array<string, mixed>
     * }
     */
    class UserRepository {
        /**
         * @param UserData $data
         * @return UserData
         */
        public function save(array $data): array {
            //Persistence and the returned value are omitted from this example.
        }
    }
?>

Type aliases can be imported across classes using @phpstan-import-type. You can centralize shared shapes in dedicated type definition classes.

<?php
    /**
     * @phpstan-import-type UserData from UserRepository
     * @phpstan-import-type OrderData from OrderRepository as Order
     */
    class InvoiceService {
        /**
         * @param UserData $user
         * @param Order $order
         */
        public function generate(array $user, array $order): void {
            //Both imported types available
        }
    }
?>

This pattern separates type contracts from implementation logic.

The type definition becomes a reusable contract, preventing drift when multiple functions share the same structure.

Advanced Type Constraints

These annotations do not validate data at runtime. They let PHPStan check more specific constraints during static analysis.

non-empty-array<T> describes an array with at least one item. key-of<T> and value-of<T> derive key and value types from an array constant. See PHPStan's documentation for array types and array shapes.

<?php
    class Status {
        public const TYPES = [
            'pending' => 1,
            'active' => 2,
            'completed' => 3
        ];
    }

    /**
     * @param key-of<Status::TYPES> $status
     * @param value-of<Status::TYPES> $code
     */
    function updateStatus(string $status, int $code): void {
        //$status is 'pending'|'active'|'completed'
        //$code is 1|2|3
    }
?>

These annotations let static analysis catch some type mismatches before runtime and can improve IDE autocomplete. They do not remove the need to validate untrusted data at runtime.


Comments ({{ modelContent.total_comments }})