为什么这里的答案是 15? [英] Why is the answer 15 here?
问题描述
对于下面的代码片段,答案是 15.
For the following code snippet the answer is 15.
$a = '5 USD';
$b = 10;
echo $a + $b;
但是在变量$a
中,如果5
在'USD'
之间或'USD'
之后> 输出为 10
.为什么会这样?
But in the variable $a
, if 5
is in between 'USD'
or after 'USD'
the output is 10
. Why is it so?
推荐答案
来自 php.net:
在数字上下文中计算字符串时,结果值和类型确定如下.
When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
如果字符串不包含任何字符."、e"或E"并且数值符合整数类型限制(定义为PHP_INT_MAX),字符串将被评估为一个整数.在所有其他在这种情况下,它将被评估为浮点数.
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
该值由字符串的初始部分给出.如果字符串以有效的数字数据开头,这将是使用的值.否则,该值将为 0(零).有效的数字数据是可选符号,后跟一个或多个数字(可选包含一个小数点),后跟一个可选的指数.指数是一个e"或E"后跟一位或多位数字.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
字面意思:
$a + $b
表示numeric + numeric
."5 USD"
以有效的数字数据开头,因此 PHP 将其转换为5
."USD 5"
或"U5SD"
以无效有效数字数据开头,因此 PHP 将其转换进入0
.
$a + $b
meansnumeric + numeric
."5 USD"
starts with a valid numeric data, so PHP converts it into5
."USD 5"
or"U5SD"
starts with not valid numeric data, so PHP converts it into0
.
<小时>
UPDv1:
<?php
header('Content-Type: text/plain');
function plus($a, $b){
echo $a, ' + ', $b, ' = ', $a + $b, PHP_EOL;
}
plus('5 frogs', 3); // 5 + 3 = 8
plus('frogs: 5', 3); // 0 + 3 = 3
plus('f5rogs', 3); // 0 (not HEX) + 3 = 3
plus('0xF5', 3); // 245 (HEX) + 3 = 248
plus('0011b', 3); // 11 (not BIN) + 3 = 14
plus('1E5', '1.2xx'); // 100000 (FLOAT) + 1.2 (FLOAT) = 100001.2
plus('true', 2); // 0 (not BOOL) + 2 = 2
?>
<小时>
另外,看看这个:php字符串数字连接搞砸了.
UPDv2:
无论零填充效果如何,PHP 都无法"将字符串值类型转换为八进制.尽管如此,如前所述,PHP 能够将字符串类型转换为十六进制.
There is "no way" for PHP to typecast string value to octal, regardless of zero-fill effect. Still, as mentioned before, PHP able to typecast string to hexadecimal.
<?php
header('Content-Type: text/plain');
function plus($a, $b){
echo $a, ' + ', $b, ' = ', $a + $b, PHP_EOL;
}
plus(008, 12); // Invalid octal, PHP assumes it is 0. Result: 12.
plus('008', 12); // Invalid octal? No, it is decimal. Result: 20.
plus(0x0F, 1); // Valid hexadecimal. Result: 16.
plus('0x0F', 1); // Valid hexadecimal. Result: 16.
plus('0x0X', 1); // Invalid hexadecimal, PHP assumes it is 0. Result: 1.
?>
字符串到数字的转换"文档中未提及.
这篇关于为什么这里的答案是 15?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!