请看以下代码:
$a = 'Test';
echo ++$a;
这将输出:
Tesu
问题是,为什么?
我知道“u”在“t”之后,但为什么它不打印出“1”?
PHP文档:
此外,被递增或递减的变量将被转换为适当的数字数据类型 - 因此,以下代码将返回1,因为字符串Test首先被转换为整数0,然后递增。
PHP在处理字符变量的算术运算时遵循Perl的约定,而不是C的约定。例如,在Perl中,'Z'+1会变成'AA',而在C中,'Z'+1会变成'['(ord('Z')==90,ord('[')==91)。请注意,字符变量可以递增但不能递减,即使递增也只支持纯ASCII字符(a-z和A-Z)。
"a" + 1
在"z"
之后是"b"
,依此类推。"Test"
之后是"Tesu"
。<?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;
?>
上述代码利用了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
。前面的内容意味着请注意,字符变量可以递增但不能递减,即使只支持纯ASCII字符(a-z和A-Z)。
echo --$a;
实际上会打印出Test
,而不会改变字符串本身。
1
可能会让人感到奇怪。 - David Titarenco$a + 1
不等同于++$a
或者$a++
。 - BoltClock