Skip to content

ArrayUniqueCanBeUsed ​

info on by default quick-fix PHP ≥ 7.2

Group: Control flow · PhpStorm name: ArrayUniqueCanBeUsedInspection

Counting occurrences with array_count_values() just to take the keys or the number of keys is an indirect way of deduplicating. Since PHP 7.2 array_unique() is fast and says what is meant: array_values(array_unique($a)) or count(array_unique($a)).

Example ​

(PHP level 7.2)

php
<?php
function tally(array $votes, $batch) {
    $names = array_keys(array_count_values($votes['names']));
    $total = \count(\array_count_values(load($batch)));

    $flip  = array_flip(array_count_values($votes['names']));
    $pair  = count(array_count_values($votes['names'], $batch));
    $wrap  = count((array_count_values($votes['names'])));
    $obj   = $batch->count(array_count_values($votes['names']));
    return [$names, $total, $flip, $pair, $wrap, $obj];
}
php
<?php
function tally(array $votes, $batch) {
    $names = array_values(array_unique($votes['names']));
    $total = \count(\array_unique(load($batch)));

    $flip  = array_flip(array_count_values($votes['names']));
    $pair  = count(array_count_values($votes['names'], $batch));
    $wrap  = count((array_count_values($votes['names'])));
    $obj   = $batch->count(array_count_values($votes['names']));
    return [$names, $total, $flip, $pair, $wrap, $obj];
}

Reported:

  • line 3: Use 'array_values(array_unique($votes['names']))' instead (array_unique() is fast since PHP 7.2).
  • line 4: Use 'count(array_unique(load($batch)))' instead (array_unique() is fast since PHP 7.2).

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore ArrayUniqueCanBeUsed

/**
 * @noinspection ArrayUniqueCanBeUsedInspection
 */

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