Concatenation Operator Precedence Changes in PHP 8.0

In versions prior to PHP 8.0, the precedence of concatenation (.), + and - operators are equal and these operators are evaluated from left to right.

Consider the following line of code:

<?php

echo 'Sum: ' . 5 + 6;

In PHP 7.3 this code produces a warning and expression evaluates to 6:

Warning: A non-numeric value encountered in main.php on line 3
6

It’s the same as writing the following line of code:

<?php

echo ('Sum: ' . 5) + 6;

In PHP 7.4 this code also produces a deprecation notice because concatenation (.) and +/- operators was used in the same expression without parenthesis:

Deprecated: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence in main.php on line 3
Warning: A non-numeric value encountered in main.php on line 3
6

Since PHP 8.0, the -/+ operators takes a higher precedence than concatenation (.) operator. It means that the following line of code will be evaluated to Sum: 11:

<?php

echo 'Sum: ' . 5 + 6;

It’s interpreted like this:

<?php

echo 'Sum: ' . (5 + 6);

Leave a Comment

Your email address will not be published. Required fields are marked *