PHP 字符串和算术运算的连接 [英] PHP concatenation of strings and arithmetic operations

查看:39
本文介绍了PHP 字符串和算术运算的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不久前开始学习 PHP,但遇到了这个问题:

I started learning PHP not too long ago and I ran into this issue:

<?php

$a = 1;
$b = 2;

echo "$a * $b  = " . $a * $b;
echo "<br />";

echo "$a / $b  = " . $a / $b;
echo "<br />";

echo "$a + $b  = " . $a + $b;
echo "<br />";

echo "$a - $b  = " . $a - $b;
echo "<br />";

我得到以下输出:

1 * 2 = 2
1 / 2 = 0.5
3
-1

输出中的最后两行不是我所期望的.

The last two lines in the output are not what I would expect.

这是为什么?这些表达式是如何计算的?我正在努力更好地理解该语言.

Why is this? How are these expressions evaluated? I'm trying to get a better understanding of the language.

推荐答案

这是因为连接运算符有一个 比加法或减法运算符有更高的优先级,但乘法和除法的优先级高于串联.

This is happening because the concatenation operator has a higher precedence than the addition or subtraction operators, but multiplication and division have a higher precedence then concatenation.

所以,你真正执行的是:

So, what you're really executing is this:

echo ("$a + $b  = " . $a) + $b;
echo ("$a - $b  = " . $a) - $b;

在第一种情况下,它变成了这样:

In the first case, that gets turned into this:

"1 + 2 = 1" + $b

哪个 PHP 尝试将 "1 + 2 = 1" 转换为数字(因为 输入 juggling) 并得到 1,将表达式变成:

Which PHP tries to convert "1 + 2 = 1" into a number (because of type juggling) and gets 1, turning the expression into:

1 + 2

这就是你得到 3 的原因.同样的逻辑可以应用于减法条件.

Which is why you get 3. The same logic can be applied to the subtraction condition.

相反,如果您在计算前后加上括号,您将获得所需的输出.

Instead, if you put parenthesis around the calculations, you'll get the desired output.

echo "$a + $b  = " . ($a + $b);
echo "$a - $b  = " . ($a - $b);

这篇关于PHP 字符串和算术运算的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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