1.2.208. Concat And Addition

Precedence between addition and concatenation has changed. In PHP 7.4, addition has precedence, and before, addition and concatenation had the same precedence.

From the RFC : Currently the precedence of '.', '+' and '-' operators are equal. Any combination of these operators are simply evaluated left-to-right.

This is counter-intuitive though: you rarely want to add or subtract concatenated strings which in general are not numbers. However, given PHP’s capability of seamlessly converting an integer to a string, concatenation of these values is desired.`` This analysis reports any addition and concatenation that are mixed, without parenthesis. Addition also means substraction here, aka using + or -.

The same applies to bitshift operations, << and >>. There is no RFC for this change.

<?php
// Extracted from the RFC
echo "sum: " . $a + $b;

// current behavior: evaluated left-to-right
echo ("sum: " . $a) + $b;

// desired behavior: addition and subtraction have a higher precendence
echo "sum :" . ($a + $b);

?>

See also Change the precedence of the concatenation operator.

1.2.208.1. Suggestions

  • Add parenthesis around the addition to ensure its expected priority

  • Move the addition outside the concatenation

1.2.208.2. Specs

Short name

Php/ConcatAndAddition

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior, CompatibilityPHP53, CompatibilityPHP54, CompatibilityPHP55, CompatibilityPHP56, CompatibilityPHP70, CompatibilityPHP71, CompatibilityPHP72, CompatibilityPHP73, CompatibilityPHP74, CompatibilityPHP80, Top10

Exakat since

1.8.0

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Changed Behavior

PHP 8.0 - More

Precision

Very high

Features

addition, concatenation

Available in

Entreprise Edition, Community Edition, Exakat Cloud