 I don't know why am getting confused, can some shine more light to this part? | SoloLearn: Learn to code for FREE!

+7

# I don't know why am getting confused, can some shine more light to this part?

<?php \$a = 10; \$b = \$a++; echo \$a; ?> /* echo \$a, this part I thought it was supposed to output \$a which is 10, why is it outputting "11"? */ /* I also thought that by calling \$b the output will be " 11". */ and also what is the difference between a++; & ++a?

8 Answers

New Answer

+20

I hope this could help <?php \$a1 = 10; \$b1 = \$a1++; /*output: \$b2 = 10 and \$a1 = 11 this will pre-increment, get the value and increment \$a1 */ \$a2 = 10; \$b2 = ++\$a2; /*output \$b2 = 11; \$a2 =11; post-increment, this will increment first and place the value */ ?>

+4

\$a = 10; // defines variable a with value 10 \$b = \$a++; //defines variable, post increment var a. echo \$a; //output 11 ++a uses pre increment operator and returns value after increment ( adding 1). a++ uses post increment operator and returns value before increment (original value). b = ++a // y = 10, a = 10 b = a++ //y = 11, a = 10

+4

+3

a++ means post increment and ++a means pre increment. a++ executes after the statement and ++a executes before the statement. \$b = \$a++ here you are assigning a 10 and after the statement incrementing \$a by one, that's why you get \$b = 10 and \$a = 11

+2

Read this post https://www.sololearn.com/discuss/223343/?ref=app

+2

try this, and understand how it works : \$a = 10 \$b = \$a++ echo \$a the output is 11 echo \$b the output is 10 \$a = 10 \$b = 20 \$c = 10 echo \$b + (\$a++) the output will be 30 echo \$b + (++\$c) the output will 31

+2

https://www.sololearn.com/discuss/489143/?ref=app