PHP | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

PHP

Someone please explain the output: for ($i = 1; $i < 8; $i++) if(5 % $i==0 && $i != 1) echo 8 % $i++; else echo $i++; //output : 1337.

27th Nov 2019, 12:51 PM
A.H. Majumder 🇧🇩
A.H. Majumder 🇧🇩 - avatar
4 Answers
+ 2
$i = 1: else is executed and because of postfix 1 is printed Next iteration $i =3 cause the postfix increased the value and the for loop increased the value too. 5 %3 =2 so else is executed again. Next iteration $i = 5 (same reason as before) and now 5 %5=0 and 5 != 1 so echo 8%5 is executed cause $i++ is postfix again. 8%5=3 so 3 ist in printed. Now $i =7 and again echo is executed. In the next iteration $i would be 9 so the for condition $i <8 is wrong and for loop is ended.
27th Nov 2019, 1:32 PM
Jnn
Jnn - avatar
+ 2
* FIRST $i = 1 $i < 8 (true) 5 % $i == 0 (true) AND $i != 1 (false) * Evaluation true AND false yields false * So execute `else` block print $i (1) then increment $i => 2 $i++ in loop declaration increment $i => 3 * NEXT $i = 3 $i < 8 (true) 5 % $i == 0 (false) [because 5 % 3 => 2] * Here short circuit evaluation ignores `$i != 1` because left-hand operand evaluates to false * So execute `else` block print $i (3) then increment $i => 4 $i++ in loop declaration increment $i => 5 * NEXT $i = 5 $i < 8 (true) 5 % $i == 0 (true) AND $i != 1 (true) * Evaluation true AND true yields true * So execute `if` block print `8 % $i` (3) then increment $i => 6 $i++ in loop declaration increment $i => 7 * NEXT $i = 7 $i < 8 (true) 5 % $i == 0 (false) [because 5 % 7 => 5] * Here short circuit evaluation ignores $i != 1 (because left-hand operand evaluates to false * So execute `else` block print $i (7) then increment $i => 8 $i++ in loop declaration increment $i => 9 * NEXT $i = 9 $i < 8 (false) # Loop ends Hth, cmiiw
27th Nov 2019, 1:44 PM
Ipang
+ 2
No worries, if you learn and practice regularly you'll get the hang of it pretty soon 👍 And this was indeed a tricky one.
27th Nov 2019, 5:24 PM
Ipang
+ 1
Thanks to both of you for explaining the code. But still I have to look at your explanation again as I am not good in PHP till now.
27th Nov 2019, 5:01 PM
A.H. Majumder 🇧🇩
A.H. Majumder 🇧🇩 - avatar