SubStrUsedAsArrayAccess
warning on by default quick-fixGroup: 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. The proven negative position -1 is translated to strlen($str) - 1.
Example
php
<?php
function peek(string $buf, ?string $maybe, string|int $mixed, array $rows, int $at)
{
$a = substr($buf, $at, 1);
$b = substr($buf, -1, 1);
$c = substr($maybe, 0, 1);
$d = substr($mixed, 2, 1);
return [$a, $b, $c, $d];
}php
<?php
function peek(string $buf, ?string $maybe, string|int $mixed, array $rows, int $at)
{
$a = substr($buf, $at, 1);
$b = ($buf[strlen($buf) - 1] ?? '');
$c = ($maybe[0] ?? '');
$d = substr($mixed, 2, 1);
return [$a, $b, $c, $d];
}Reported:
- line 5: Use '($buf[strlen($buf) - 1] ?? '')' (string offset access) instead.
- line 6: Use '($maybe[0] ?? '')' (string offset access) instead.
- line 7: Use '$mixed[2]' (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
*/