Skip to content

SubStrUsedAsArrayAccess ​

warning on by default quick-fix

Group: Performance · PhpStorm name: SubStrUsedAsArrayAccessInspection

Extracting a single character with substr($str, $i, 1) costs a function call; string offset access ($str[$i]) reads the same byte directly. Negative positions are translated to strlen($str) - n.

Example ​

At PHP 7.0+:

php
<?php
class Token {
    /** @var string */
    public $raw = '';
}
function peek(string $buf, int $at, int $back, string $key, Token $t, $any)
{
    $a = substr($buf, $at, 1);
    $b = \substr($buf, -1, 1);
    $c = substr($t->raw, 0, 1);

    $d = mb_substr($buf, $at, 1);
    $e = substr($buf, $at, 2);
    $f = substr(strrev($buf), 0, 1);
    $g = substr($at, 0, 1);
    $h = substr($any, 0, 1);
    $i = substr($buf, -3, 1);
    $j = substr($buf, -$back, 1);
    $k = substr($buf, $key, 1);
    return [$a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k];
}
php
<?php
class Token {
    /** @var string */
    public $raw = '';
}
function peek(string $buf, int $at, int $back, string $key, Token $t, $any)
{
    $a = ($buf[$at] ?? '');
    $b = ($buf[strlen($buf) - 1] ?? '');
    $c = ($t->raw[0] ?? '');

    $d = mb_substr($buf, $at, 1);
    $e = substr($buf, $at, 2);
    $f = substr(strrev($buf), 0, 1);
    $g = substr($at, 0, 1);
    $h = substr($any, 0, 1);
    $i = substr($buf, -3, 1);
    $j = substr($buf, -$back, 1);
    $k = substr($buf, $key, 1);
    return [$a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k];
}

Reported:

  • line 8: Use '($buf[$at] ?? '')' (string offset access) instead.
  • line 9: Use '($buf[strlen($buf) - 1] ?? '')' (string offset access) instead.
  • line 10: Use '($t->raw[0] ?? '')' (string offset access) instead.

Configure ​

In custos.json:

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

Suppress ​

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

php
// @custos-ignore SubStrUsedAsArrayAccess

/**
 * @noinspection SubStrUsedAsArrayAccessInspection
 */

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