Search code examples
phpphpstormphpdoc

Specify an array index type


How can I specify an array index and sub-index type? Note: I will use it with PHPStorm.

Array example:

function name ($options) {
    // $options['length']        => integer
    // $options['more']          => array
    // $options['more']['test1'] => boolean
    // $options['more']['test2'] => boolean
}

Example (that not works):

/**
 * @param array $options
 *      @var int   $length
 *      @var array $more
 *          @var bool $test1
 *          @var bool $test2
 */

Solution

  • In general, PhpStorm only support simple syntax, just as Sam has stated, e.g.

    /**
     * @param string[] $options
     */
    

    The code above described parameter which is array of strings.


    Install Options completion plugin -- it supports new proposed syntax for hashes (describing array keys and its' types) in PHPDoc: https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#7-describing-hashes

    This plugin will add code completion for array keys.

    <?php
    class Element {
        /**
         * Initializes this class with the given options.
         *
         * @param array $options {
         *     @var bool   $required Whether this element is required
         *     @var string $label    The display name for this element
         * }
         */
        public function __construct(array $options = array())
        {
            // some code here
        }
    }
    
    
    new Element(['label' => 'Bob', '|' ]);
    //                              | Ctrl+Space will show supported attributes
    

    NOTE: Main purpose of this plugin is to offer array keys completion -- I'm not sure how well it supports type resolutions for each of array elements (in case if they are different like in your example).