1.2.885. Optimize Explode()

Limit explode() results at call time. explode() returns an array, after breaking the argument into smaller strings, with a delimiter.

By default, explode() breaks the whole string into smaller strings, and returns the array. When not all the elements of the returned array are necessary, using the third argument of explode() speeds up the process, by removing unnecessary work. Limiting explode() has no effect when the operation is already exact : it simply prevents explode() to cut more than needed if the argument is unexpectedly large.

This optimisation applies to split(), preg_split() and mb_split(), too.

This is a micro optimisation, unless the exploded string is large.

<?php

$string = '1,2,3,4,5,';

// explode() returns 2 elements, which are then assigned to the list() call.
list($a, $b) = explode(',', $string, 2);

// explode() returns 6 elements, only two of which are then assigned to the list() call. The rest are discarded.
list($a, $b) = explode(',', $string, 2);

// it is not possible to skip the first elements, but it is possible to skip the last ones.
echo explode(',', $string, 2)[1];

// This protects PHP, in case $string ends up with a lot of commas
$string = foo(); // usually '1,2' but not known
list($a, $b) = explode(',', $string, 2);
?>

See also Cryptography Extensions.

1.2.885.1. Suggestions

  • Add a limit to explode() call

1.2.885.2. Specs

Short name

Performances/OptimizeExplode

Rulesets

All, Changed Behavior, Performances

Exakat since

2.1.9

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

crypto

Available in

Entreprise Edition, Exakat Cloud