Skip to content

TypeUnsafeArraySearch ​

info on by default

Group: Type compatibility · PhpStorm name: TypeUnsafeArraySearchInspection

in_array() and array_search() compare loosely unless their third argument is true, so '1abc', 1, true and '1' can all "match". Asking for the third argument forces the author to decide whether loose matching is really wanted.

Example ​

php
<?php
function pick($code, array $allowed) {
    $r = [];
    $r[] = in_array($code, $allowed);
    $r[] = \array_search(7, []);
    $r[] = array_search($code, ['404', '500']);
    $r[] = in_array($code, ['  ']);
    $r[] = in_array($code, ['x' => 'yes']);
    $r[] = in_array($code, ['on', 1]);

    /** @var string $color */
    /** @var array $palette */
    $r[] = in_array($color, $palette);

    /** @var string $tone */
    /** @var string[] $tones */
    $r[] = in_array($tone, $tones);

    $r[] = in_array($code, ['draft', "final"]);
    $r[] = array_search($code, array('v1', 'v2'));
    $r[] = in_array($code, $allowed, false);
    $r[] = array_search($code, $allowed, true);
    $r[] = in_array($code);
    return $r;
}

Reported:

  • line 4: Pass a third argument to say whether this search must be type-strict.
  • line 5: Pass a third argument to say whether this search must be type-strict.
  • line 6: Pass a third argument to say whether this search must be type-strict.
  • line 7: Pass a third argument to say whether this search must be type-strict.
  • line 8: Pass a third argument to say whether this search must be type-strict.
  • line 9: Pass a third argument to say whether this search must be type-strict.
  • line 13: Pass a third argument to say whether this search must be type-strict.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore TypeUnsafeArraySearch

/**
 * @noinspection TypeUnsafeArraySearchInspection
 */

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