Skip to content

CompactCanBeUsed ​

info off by default quick-fix

Group: Control flow · PhpStorm name: CompactCanBeUsedInspection

An array literal whose every entry maps a string key to the variable of the same name (['id' => $id, 'tag' => $tag]) can be written as compact('id', 'tag'), which avoids repeating each name twice.

Example ​

php
<?php
function payload($id, $tag, $note) {
    $a = ['id' => $id, 'tag' => $tag];
    $b = array("id" => $id, 'note' => $note, 'tag' => $tag,);
    send(['note' => $note, 'id' => $id]);

    $c = ['id' => $id];
    $d = ['id' => $tag, 'tag' => $id];
    $e = ['id' => $id, 'tag' => trim($tag)];
    $f = ['id' => $id, 'tag' => $tag, $note];
    $g = ['ID' => $id, 'tag' => $tag];
    ['id' => $id, 'tag' => $tag] = load();
    return [$a, $b, $c, $d, $e, $f, $g];
}
php
<?php
function payload($id, $tag, $note) {
    $a = compact('id', 'tag');
    $b = compact("id", 'note', 'tag');
    send(compact('note', 'id'));

    $c = ['id' => $id];
    $d = ['id' => $tag, 'tag' => $id];
    $e = ['id' => $id, 'tag' => trim($tag)];
    $f = ['id' => $id, 'tag' => $tag, $note];
    $g = ['ID' => $id, 'tag' => $tag];
    ['id' => $id, 'tag' => $tag] = load();
    return [$a, $b, $c, $d, $e, $f, $g];
}

Reported:

  • line 3: Replace with 'compact('id', 'tag')'.
  • line 4: Replace with 'compact("id", 'note', 'tag')'.
  • line 5: Replace with 'compact('note', 'id')'.

Configure ​

In custos.json:

json
{
  "rules": {
    "CompactCanBeUsed": {
      "enabled": true
    }
  }
}

Suppress ​

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

php
// @custos-ignore CompactCanBeUsed

/**
 * @noinspection CompactCanBeUsedInspection
 */

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