Arithmetic operation within string concatenation without parenthesis causes strange result

后端 未结 3 604
星月不相逢
星月不相逢 2021-01-13 17:34

Consider the following line of code:


The output of that is 3, which is the expec

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-13 17:49

    In this code:

    echo '10 - 7 = '.$x-$y;
    

    The concatenation takes precedence, so what you're left with is this:

    echo '10 - 7 = 10'-$y;
    

    Because this is trying to perform integer subtraction with a string, the string is converted to an integer first, so you're left with something like this:

    echo (int)'10 - 7 = 10'-$y;
    

    The integer value of that string is 10, so the resulting arithmetic looks like this:

    echo 10-$y;
    

    Because $y is 7, and 10 - 7 = 3, the result being echoed is 3.

提交回复
热议问题