1.2.118. Casting Ternary

Type casting has a precedence over ternary operator, and is applied first. When this happens, the condition is cast, although it is often useless as PHP will do it if needed.

This applies to the ternary operator, the coalesce operator ?: and the null-coalesce operator ??. The last example generates first an error Undefined variable: b, since $b is first cast to a string. The result is then an empty string, which leads to an empty string to be stored into $a. Multiple errors cascade.

<?php
    $a = (string) $b ? 3 : 4;
    $a = (string) $b ?: 4;
    $a = (string) $b ?? 4;
?>

See also Operators Precedence.

1.2.118.1. Suggestions

  • Add parenthesis around the ternary operator

  • Skip the casting

  • Cast in another expression

1.2.118.2. Specs

Short name

Structures/CastingTernary

Rulesets

All, Analyze, CE, CI-checks

Exakat since

1.8.0

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

ternary, cast

Available in

Entreprise Edition, Community Edition, Exakat Cloud