+ 4

Can somebody explain me this code?

<?php Function fun(){ $x=0; Echo $x; $x++; } Fun(); Fun(); Fun(); ?> It will output 000 but again i have no ideea why. Thanks

11th Aug 2018, 9:18 PM
razvan
razvan - avatar
6 Antworten
+ 5
It doesn't matter that $x++ is placed after the echo (I mean: it doesn't mean that it's not achived) but after it increments $x then in the next loop the line $x=0; will set $x to zero again (btw, It wouldn't if $x was a static variable but it's not). joshua johns and razvan you can read Eduardo's answer again he is right and for me that answer is clear, but I decided to write my own after seeing that it looks like you are paying to much attention that $x++ is after the line with echo (of course you won't get incremented variable in the output if $x++ will be written after the echo (echo $x;) it's obvious... but the tricky part here (in this question) that you are re_setting $x to zero each time the loop starts and so if you will write $x++ before the line with "echo" you will get incremented value (variable) 1 of course... but it doesn't mean that you'll get 123 as an output of those 3 function calls, because you'll...
20th Aug 2018, 6:15 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 4
well you call the function fun 3 times and always your function set the x value to 0. Basically you are print 0 the first time, then x increase but the function ends, and the same after.
11th Aug 2018, 9:34 PM
Eduardo
Eduardo - avatar
+ 4
...because you'll get 111 as an output of 3 function calls. Can I explain something else here? (Or was it not needed at all as you do understand it that way?) ☺
20th Aug 2018, 6:18 PM
Andrew Harchenko (Tomsk)
Andrew Harchenko (Tomsk) - avatar
+ 4
Andrew Harchenko (Tomsk) thank you. i understood now. no further questions :) thanks again.
20th Aug 2018, 8:10 PM
razvan
razvan - avatar
+ 2
right..i understand now..so $x++ will not count because this code line is writen after the echo..and then the function ends without any echo..thank you
11th Aug 2018, 9:40 PM
razvan
razvan - avatar
+ 1
The code outputs 000 because there is no condition set so as to increment to be achieved.i.e the increment comes after echo statement which makes no sense
20th Aug 2018, 7:52 AM
Murithi Joshua
Murithi Joshua  - avatar