简体   繁体   中英

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?

$a = 5;
$b = $a;

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

Does it echo $a then add 1 to it? Why doesn't it echo the result?

EDIT: Another simple example for anyone viewing:

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

Produces 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.

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.

Here is the $a++ explanation:

++$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?

Because $a++ is post increment it return value and then increment the value.

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.

If you do preincremenation firstly value to $a is added then it is returned in that cause you will see 66 and 77

echo ++$a . ++$b;

will print 66 as you probably expected.

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.

Morover, if you use reference

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

 echo $a++ . $b++;

It will output 56

and

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

 echo ++$a . ++$b;

will output 77 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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