Redundant Cast

ID

php.redundant_cast

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Php

Tags

code-style, code_smell

Description

Reports a type cast whose operand already has the cast’s target type, so the cast performs no conversion. Because PHP is dynamically typed and most expression types cannot be known statically, only structurally certain cases are flagged: a cast of a literal that is already of the target type ((int) 5, (string) 'x', (bool) true, (float) 1.5, (array) [1, 2]) and a cast that directly wraps another cast to the same type ((int)(int)$x).

Rationale

A redundant cast adds visual noise and can mislead a reader into thinking a conversion is taking place. Removing it makes the intent clearer and avoids the false impression that the operand had a different type. Genuine conversions — those that change the value or its representation, such as (string) 42 or (int) '42' — are left untouched.

<?php
$a = (int) 5;            // FLAW - the literal 5 is already an integer
$b = (string) 'name';    // FLAW - the literal is already a string
$c = (int)(int) $value;  // FLAW - the inner cast already yields an integer

$d = (int) '42';         // OK - parsing a string into an integer
$e = (string) 42;        // OK - rendering an integer as a string
$f = (int) $value;       // OK - $value type is not known statically

Remediation

Delete the redundant cast and keep the operand as written. When two casts are nested and the inner one already produces the target type, drop the outer cast.

References