duanlongling5308 2014-12-20 22:18 采纳率: 0%
浏览 31

Echo声明没有出来,因为我想要它[重复]

This question already has an answer here:

This code only prints out '17' instead of "10 + 7 = 17". Why is this? And how can i solve this.

<?

$x = 10;
$y = 7;

echo $x . '+' . $y . '=' . $x+$y;

?>
</div>
  • 写回答

2条回答 默认 最新

  • 「已注销」 2014-12-20 22:20
    关注

    What you should understand is that echo won't do anything until the result of the whole expression given to it is evaluated. This expression contains both . and + operators - the first one concatenates its operands (glues two strings together), the second adds numbers.

    Now, you might think that + operator has a higher precedence than of . one - in other words, that result of $x + $y will be calculated before (eventually) glued to the rest of the string. But it's not. So we can say this statement is actually treated as...

    echo ($x . '+' . $y . '=' . $x) + $y;
    

    In other words, the result of all the string concatenation is added (converted to number) to $y, and only the result of this operation is printed.

    The result of $x . '+' . $y . '=' . $x is '10+7=10', and it doesn't look like something that might be added. But guess what, PHP wants to be nice to you - and it assumes that you actually wanted to extract the first digits of a string when you tried to convert it to a number. So the whole line is treated as number 10. When added to 7, it's just 17 - that's why you got 17 echoed.

    One possible workaround is getting rid of ., using , operator instead (as its precedence is lower - in fact, it's the lowest among operators):

    echo $x, '+', $y, '=', $x + $y;
    

    It could be simplified if one remember about such a handy feature of PHP as string interpolation:

    echo "$x + $y = ", $x + $y;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题