1.2.1049. Reuse Existing Variable

A variable is already holding the content that is calculated again : it could be used again.

It is recommended to use the cached value. This saves some computation, in particular when used in a loop, and speeds up the process. This is called memoization. Some expressions are not idempotent, and should not be cached. For example, calls to time() or fgets() return different values with the same parameters.

This may be a micro-optimisation.

<?php

function foo($a) {
    $b = strtolower($a);

    // strtolower($a) is already calculated in $b. Just reuse the value.
    if (strtolower($a) === 'c') {
        doSomething();
    }
}

?>

1.2.1049.1. Suggestions

  • Reuse the existing variable

1.2.1049.2. Specs

Short name

Structures/ReuseVariable

Rulesets

All, Suggestions

Exakat since

1.1.4

PHP Version

All

Severity

Minor

Time To Fix

Slow (1 hour)

Precision

High

Features

memoization

Available in

Entreprise Edition, Exakat Cloud