1.2.67. Avoid Substr() One

Use array notation $string[$position] to reach a single byte in a string.

There are two ways to access a byte in a string : substr() and $v[$pos].

The second style is more readable. It may be up to four times faster, though it is a micro-optimization. It is recommended to use it.

PHP 7.1 also introduces the support of negative offsets as string index : negative offset are also reported. Beware that substr() and $v[$pos] are similar, while mb_substr() is not. The first function works on bytes, while the latter works on characters.

<?php

$string = 'ab人cde';

echo substr($string, $pos, 1);
echo $string[$pos];

echo mb_substr($string, $pos, 1);

// when $pos = 1
// displays bbb
// when $pos = 2
// displays ??人

?>

1.2.67.1. Suggestions

  • Replace substr() with the array notations for strings.

  • Replace substr() with a call to mb_substr().

1.2.67.2. Specs

Short name

Structures/NoSubstrOne

Rulesets

All, Analyze, CE, CI-checks, CompatibilityPHP71, Performances, Suggestions, Top10

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

Very high

Examples

ChurchCRM, LiveZilla

Available in

Entreprise Edition, Community Edition, Exakat Cloud