The logic behind how PHP interprets the concatenation of string and numbers?

5

I was doing a question quiz for the PHP certification and there was a question that left me wondering:

What will be the output of the following code snippet?

<?php
    echo 'hello'. 1 + 2 . '34';
?>

In short: The output will be 234. I ran via the command line with PHP 7.0 and 5.6 to confirm and the result continued the same .

I have not yet found a logic of how PHP came up with this result and I would like to understand. If you can explain, thank you.

NOTE: If this is not the place for this question, please comment that I will delete it.

    
asked by anonymous 09.08.2017 / 15:02

3 answers

6

The question checks your knowledge about two aspects of the language: how PHP treats strings within a mathematical operation - that is, how cast string to a number - and the precedence of the operators.

The first aspect was commented on in the other answers and is very well discussed in:

Why is the expression "2 + '6 apples'' equal to 8? p>

In short, when evaluating a string to convert it to a numeric value, PHP will check content from left to right. If the first few characters are a valid numeric value, then it is kept as a result. If it is not a valid value, the return will be 0.

var_dump((float) "1foo");    // float(1)
var_dump((float) "1.9foo");  // float(1.9)
var_dump((float) "foo3.14"); // float(0)

The second aspect, not mentioned in the other answers and fundamental to the correct analysis is the precedence of the operators. The operators used are concatenation, . , and addition, + . When checking the operators precedence table in documentation :

Noticethatbothoperatorshavethesameprecedence,sotheexpressionwillbeparsedfromlefttoright,operatortooperator.

'hello'.1+2.'34';
  • Thefirstoperatorisconcatenation,sothevalue'hello1'isgenerated;
  • Thesecondoperatorisaddition,sothevalue'hello1'isfirstevaluatedasnumeric,returning0,beingaddedwith2,resultingin2;
  • Thethirdoperatorisconcatenation,sothevalue'234'isgenerated;
  • Thisprocessisevidentwhenevaluatingtheopcodesgeneratedby VLD :

    line     #* E I O op                           fetch          ext  return  operands
    -------------------------------------------------------------------------------------
       3     0  E >   ADD                                              ~0      'hello1', 2
             1        CONCAT                                           ~1      ~0, '34'
             2        ECHO                                                     ~1
             3      > RETURN                                                   1
    

    Note that for PHP, the first operation will occur even before the expression is evaluated; this is because both operators are constant.

    According to the site 3v4l.org , the same output is generated in all versions tested, although only in versions higher than 7.1 that a alert is issued on the conversion of a non-numeric string .

    To demonstrate how operator precedence is important in this case, simply replace addition by division. According to the precedence table, the division has a higher precedence than the concatenation, so it will be evaluated first. See:

    echo 'hello'. 1 / 2 .'34';  // Resultará: hello0.534
    

    This is because by evaluating the expression, the division will be executed before, returning the value 0.5 , and after that, the two concatenations will be executed, returning hello0.534 .

        
    09.08.2017 / 15:34
    5

    First PHP concatenates the value hello plus the number 1 it generates an invalid number it is then converted to zero then it performs the count 0 + 2 and counts the result of the sum with 34 ending with the string 234 .

    echo 'hello'. 1 + 2 .'34';
      ------------^   ^--------
        1 parte         2 parte 
        valor: 0    +   valor: 2
    

    This code is the equivalent of this:

    echo ('hello'. 1) + 2 .'34';
    

    Relationships:

    Why is the expression "2 + '6 apples'' equal to 8? p>

    Mathematical operation between string and number in php

        
    09.08.2017 / 15:08
    3

    The problem is that when PHP converts strings to number it gives 0 if the string does not have digits at startup. That is:

    echo intval('4string'); // 4
    echo intval('string4'); // 0
    echo intval('string'); // 0
    

    So what happens is:

    • concatenates the first string with number gives 'hello1',
    • then you see the + operator, it converts hello1 to number (which gives 0),
    • then add that 0 to 2 (which gives 2),
    • and finally concatenate 2 with the string 34 .
    09.08.2017 / 15:13