Skip to content

MissingArrayInitialization ​

warning on by default

Group: Probable bugs · PhpStorm name: MissingArrayInitializationInspection

Appending to a local array ($list[] = …) deep inside nested loops without ever initialising it means the variable is undefined (null) when nothing is appended, and its contents leak between outer iterations if it is meant to be reset. The array should be initialised explicitly at the right place.

Example ​

php
<?php
function collect(array $groups, $limit) {
    for ($n = 0; $n < $limit; ++$n) {
        do {
            $bucket[] = $n;
            $bucket[$n][] = $limit;
        } while (false);
    }

    foreach ($groups as $group) {
        $flat[] = $group;
    }

    $done = [];
    foreach ($groups as $group) {
        foreach ($group as $item) {
            $done[] = $item;
            $limit[] = $item;
            $group[] = 0;
            $this->seen[] = $item;
        }
    }

    return function ($extra) use ($done) {
        while (true) {
            foreach ($extra as $e) {
                $done[] = $e;
                $extra[] = $e;
            }
        }
    };
}

foreach ($a as $x) {
    foreach ($x as $y) {
        $global[] = $y;
    }
}

Reported:

  • line 5: Array '$bucket' is never initialised; initialise it before the loops.
  • line 6: Array '$bucket' is never initialised; initialise it before the loops.

Configure ​

In custos.json:

json
{
  "rules": {
    "MissingArrayInitialization": {
      "enabled": false
    }
  }
}

Suppress ​

Before the statement or declaration (or the first statement of the file), either of:

php
// @custos-ignore MissingArrayInitialization

/**
 * @noinspection MissingArrayInitializationInspection
 */

Released under the MIT License. Rule catalogue modelled on Php Inspections (EA Extended); independent clean-room implementation.