+ 5
Can anyone explain to me why the output of the code below is /* 6 */? I tink the answer should be 5...
$x=2; $y = ++$x; echo $x + $y. php question by xcrocodile
13 Respostas
+ 11
$y = ++$x
After this statement, both $y and $x will be 3 since it's pre-increment.
https://www.sololearn.com/discuss/407846/?ref=app
+ 9
Basically, when you do your operation on $y, it's increasing x by 1, which makes it 3. Thus $y is 3 and $x is now 3. 3 + 3 is 6.
https://code.sololearn.com/wbSIb4u60wjV/#php
<?php
$x = 2;
echo "Original var x value: " . $x;
echo "<br>";
$y = ++$x;
echo "Var y value (y = ++x): " . $y;
echo "<br>";
echo "Var x value (after ++x): " . $x;
echo "<br>";
$sum = $x + $y;
echo "End result (x + y): " . $sum;
?>
+ 8
@Netkos.
thnx man.
It's not entirely clear to me. Bt I'll still analyze ur code further
+ 6
the value of $x and $y become 3 after 2 line then answer is 3+3 =6 ++$x increases the value of $x by 1 and become 3 and due to pre increment $y =3 that's why answer is 6 not 5 plz replace the ++x by ++$x
+ 6
As far as I am aware ++$x increments the value of $x changing it from 2 to 3. In effect your second line of code changes the value held in variable $x t0 3 which is then assigned to $y so that both $x and $y now hold the value 3 and so you get 6 being printed by the echo statement.
+ 5
@Singh. really really helpful.
Thank alot. like the simplicity of the code.
+ 4
@Vince
As others explained a bit better, when you do ++$x, you're incremented the variable $x by 1, which took it from a value of 2 to a value of 3. That value of 3 is stored in $y, but it's also stored in $x because you incremented the variable $x itself. That's why it ends up as 3 + 3, it's because $x and $y both equal 3 after you increment $x by 1.
+ 4
@richard && Yasmin.
thnx alot
+ 3
I'm tink the answer should be 5...
since
++$x ==3
and y=$x : => y=3
echo $ x + $y => 2+3 ==5
+ 3
@Sign. thnx man
nw I get it.
/^ and also for the correction. ** ++$x **
+ 3
man it's @singh not @sign btw hope you will understand this concept.
+ 3
Sorry. autocorrection on me fone.
@singh
+ 2
https://code.sololearn.com/wMo2pP0jW8yk/?ref=app
in this code you can check the value of $x after 2nd line. I have also added explaination for pre increment and post increment .well this is my first php code.