简体   繁体   English

增加字符串会产生意外结果

[英]Incrementing a string producing unexpected results

I was just playing around with PHP, can someone please explain to me why the code below prints out 5566 instead of 6666? 我只是玩PHP,有人可以向我解释为什么下面的代码打印出5566而不是6666?

$a = 5;
$b = $a;

echo $a++ . $b++;
echo "\n";
echo $a++ . $b++;

Does it echo $a then add 1 to it? 它回显$ a然后加1吗? Why doesn't it echo the result? 为什么不回应结果呢?

EDIT: Another simple example for anyone viewing: 编辑:任何人查看的另一个简单示例:

$a = 5;
$b = $a++;
echo $a++ . $b;

Produces 65 产生65

it should be echoing out 它应该回应出来

 55
 66

because when you place ++ after (suffix) then the increment is done after the statment is executed. 因为当你将++放在(后缀)之后,然后在执行语句后完成增量。 if you want 如果你想

 66
 66

then do 然后做

$a = 5;
$b = $a;

echo ++$a . ++$b;
echo "\n";
echo $a++ . $b++;

It is a POST-INCREMENT OPERATOR so the value is first being used(ie 5) and then incremented so you are getting 5566. 它是一个POST-INCREMENT OPERATOR所以首先使用该值(即5),然后递增,这样你就得到了5566。

echo $a++ . $b++;  // echo 55 and then a becomes 6 , b becomes 6
echo "\n";
echo $a++ . $b++; // echo 66

In Your code, IN first echo it returns the $a 's value after that it increment similar to $b. 在你的代码中,IN首先回显它返回$a的值,之后它增加类似于$ b。

Here is the $a++ explanation: 这是$ a ++解释:

++$a    Pre-increment   Increments $a by one, then returns $a.
$a++    Post-increment  Returns $a, then increments $a by one.
--$a    Pre-decrement   Decrements $a by one, then returns $a.
$a--    Post-decrement  Returns $a, then decrements $a by one.

Hope this will be helpful to you to understand. 希望这对您有所帮助。

Check below questions also: 检查以下问题:

Pre-incrementation vs. post-incrementation 预增量与后增量
What's the difference between ++$i and $i++ in PHP? PHP中的++ $ i和$ i ++有什么区别?

Because $a++ is post increment it return value and then increment the value. 因为$ a ++是后递增的,所以返回值然后递增值。

try: 尝试:

echo ++$a . ++$b;
echo "\n";
echo $a++ . $b++;

it's the same as 它是一样的

$a++;
$b++;
echo $a . $b;
echo "\n";
echo $a . $b;
$a++
$b++;

When you do postincrementation firstly the value is returned and then it is incremented by 1 that is why you get such results. 当你首先进行postincrementation时返回值,然后它会增加1,这就是你得到这样的结果的原因。

If you do preincremenation firstly value to $a is added then it is returned in that cause you will see 66 and 77 如果你首先进行预先增量,则会增加$ a的值,然后返回它,因为你会看到66和77

echo ++$a . ++$b;

will print 66 as you probably expected. 将按照您的预期打印66。

Notice pre incremenation/decrementaiton is faster than post that is why if you don't need to display the value firstly before incremenation/decremation use it. 注意预增量/减量比post更快,这就是为什么如果你不需要在增量/减量使用它之前首先显示该值。

Morover, if you use reference Morover,如果你使用参考

 $a = 5;
 $b = &$a;

 echo $a++ . $b++;

It will output 56 它将输出56

and

 $a = 5;
 $b = &$a;

 echo ++$a . ++$b;

will output 77 :) 将输出77 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM