字符串连接中不带括号的算术运算会导致奇怪的结果 [英] Arithmetic operation within string concatenation without parenthesis causes strange result

查看:84
本文介绍了字符串连接中不带括号的算术运算会导致奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码行:

<?php
$x = 10;
$y = 7;

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

输出为3,这是计算$ x- $ y的预期结果。但是,预期输出为:

The output of that is 3, which is the expected result of the calculation $x-$y. However, the expected output is:


10-7 = 3

10 - 7 = 3

因此,我的问题是,与计算连接的字符串发生了什么?我知道为了产生预期的结果,我需要将算术运算括在括号中:

My question therefore is, what happened to the string that I'm concatenating with the calculation? I know that in order to produce the result I expected, I need to enclose the arithmetic operation in parenthesis:

<?php
$x = 10;
$y = 7;

echo '10 - 7 = '.($x-$y);
?>

输出


10-7 = 3

10 - 7 = 3

但是由于PHP不抱怨原始代码,所以我想知道背后的逻辑是什么在这种情况下产生的输出是?琴弦去哪了?如果有人可以解释它或将我指向PHP手册中的解释位置,我将不胜感激。

But since PHP does not complain about the original code, I'm left wondering what the logic behind the produced output in that case is? Where did the string go? If anyone can explain it or point me to a location in the PHP manual where it is explained, I'd be grateful.

推荐答案

您的字符串 '10-7 =' $ x 。然后将其解释为 int ,结果为 10 ,然后为 7 减去,得到 3

Your string '10 - 7 = ' is being concatenated with $x. Then that is being interpreted as an int which results in 10 and then 7 is subtracted, resulting in 3.

有关更多说明,请尝试以下操作:

For more explanation, try this:

echo (int) ('10 - 7 = ' . 10); // Prints "10"

有关字符串到数字转换的更多信息,请参见 http://www.php.net/manual/zh-CN /language.types.string.php#language.types.string.conversion

More information on string to number conversion can be found at http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion


如果字符串以有效数字开头,这将是使用的值

If the string starts with valid numeric data, this will be the value used

这篇关于字符串连接中不带括号的算术运算会导致奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆