Unused Local Variable

ID

php.unused_local_variable

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Php

Tags

CWE:563, code-style, unused-code

Description

Reports local variables that are assigned inside a function but whose value is never read anywhere in the body. The assignment computes a result that is immediately discarded.

Rationale

A write-only variable is wasted work and a reading hazard: it looks meaningful but influences nothing, so a maintainer must trace the whole function to confirm it is inert. More often than not the dead store is the symptom of a real bug — a value that was meant to be returned or passed on and was forgotten.

The rule only reports plain assignments to a bare local variable. Augmented assignments (+=, .=) read the target and are not pure writes. Member, element and qualified targets ($this→x, $arr[0], A::$s) are out of scope. Variables interpolated inside double-quoted strings ("$value", "{$value}") count as used, as do $this and the superglobals. Functions that read variables dynamically (compact, extract, get_defined_vars, func_get_args) are skipped entirely.

<?php
function total($items)
{
    $sum = 0;
    $unused = compute();   // FLAW — assigned but never read
    foreach ($items as $item) {
        $sum += $item;     // OK — $sum is read on the next line
    }
    return $sum;
}

Remediation

Delete the assignment. If the value should have been used, add the missing logic that consumes it (for example return it, pass it on, or include it in the computation).