Skip to content

ArraySearchUsedAsInArray ​

warning on by default quick-fix

Group: Control flow · PhpStorm name: ArraySearchUsedAsInArrayInspection

array_search() returns a key (which may be 0 or '') or false. When its result is only used as a yes/no answer, in_array() expresses the intent directly and avoids the classic "key 0 is falsy" trap. Comparing its result with true is always pointless, since the function never returns true.

Example ​

php
<?php
function audit(array $roles, $who, $flag) {
    if (array_search($who, $roles)) { log_hit(); }
    while (!\array_search($who, $roles, true)) { $who = next_user(); }
    $ok = ((array_search('root', $roles))) && $flag;
    $tag = array_search($who, $roles) ? 'known' : 'stranger';

    $miss = array_search($who, $roles) === FALSE;
    $hit  = false !== array_search($who, $roles);
    $odd  = array_search($who, $roles) === true;

    $key   = array_search($who, $roles) ?: 'none';
    $other = $flag ?? array_search($who, $roles);
    $loose = array_search($who, $roles) == false;
    $wrap  = (array_search($who, $roles)) !== false;
    $one   = array_search($who);
    return $flag xor array_search($who, $roles);
}
php
<?php
function audit(array $roles, $who, $flag) {
    if (in_array($who, $roles)) { log_hit(); }
    while (!\in_array($who, $roles, true)) { $who = next_user(); }
    $ok = ((in_array('root', $roles))) && $flag;
    $tag = in_array($who, $roles) ? 'known' : 'stranger';

    $miss = !in_array($who, $roles);
    $hit  = in_array($who, $roles);
    $odd  = array_search($who, $roles) === true;

    $key   = array_search($who, $roles) ?: 'none';
    $other = $flag ?? array_search($who, $roles);
    $loose = array_search($who, $roles) == false;
    $wrap  = (array_search($who, $roles)) !== false;
    $one   = array_search($who);
    return $flag xor array_search($who, $roles);
}

Reported:

  • line 3: Use 'in_array(...)' to test membership.
  • line 4: Use 'in_array(...)' to test membership.
  • line 5: Use 'in_array(...)' to test membership.
  • line 6: Use 'in_array(...)' to test membership.
  • line 8: Use 'in_array(...)' to test membership.
  • line 9: Use 'in_array(...)' to test membership.
  • line 10: array_search() cannot return true; this comparison never changes.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore ArraySearchUsedAsInArray

/**
 * @noinspection ArraySearchUsedAsInArrayInspection
 */

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