观看以下代码:
$a = 'Test';
echo ++$a;
这将输出:Tesu
问题是,为什么?我知道“u”在“t”之后,但是为什么它不显示“1”?
PHP文档:
最佳答案
在PHP中,您可以增加字符串(但是您不能使用加法运算符来“增加”字符串,因为加法运算符会导致将字符串强制转换为int
,因此您只能使用递增运算符来“增加”字符串!...参见最后一个示例):
因此,在"a" + 1
出现在"b"
之后,"z"
就是"aa"
,依此类推。
所以"Test"
出现后"Tesu"
在使用PHP的自动类型强制时,必须注意上述几点。
自动类型强制:
<?php
$a="+10.5";
echo ++$a;
// Output: 11.5
// Automatic type coercion worked "intuitively"
?>
没有自动类型强制! (增加一个字符串):
<?php
$a="$10.5";
echo ++$a;
// Output: $10.6
// $a was dealt with as a string!
?>
如果要处理字母的ASCII序数,则必须做一些额外的工作。
如果要将字母转换为ASCII序数,请使用 ord() ,但这一次只能处理一个字母。
<?php
$a="Test";
foreach(str_split($a) as $value)
{
$a += ord($value); // string + number = number
// strings can only handle the increment operator
// not the addition operator (the addition operator
// will cast the string to an int).
}
echo ++$a;
?>
live example
上面的事实利用了字符串只能在PHP中递增的事实。不能使用加法运算符来增加它们。在字符串上使用加法运算符将导致将其强制转换为
int
,因此:使用加法运算符不能“增加”字符串:
<?php
$a = 'Test';
$a = $a + 1;
echo $a;
// Output: 1
// Strings cannot be "added to", they can only be incremented using ++
// The above performs $a = ( (int) $a ) + 1;
?>
上面将尝试在添加
Test
之前将“(int)
”转换为1
。将“Test
”转换为(int)
会导致0
。注意:您不能减少字符串:
前面的意思是
echo --$a;
实际上将打印Test
而根本不更改字符串。关于php - PHP 5.3中++运算符的奇怪行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3799549/