Pages

Sunday, September 15, 2013

PHP-Loop Queston's

1. for($i=1;$i++;$i<100)
echo $i;

2. for($i=0;$i++;$i<100)
echo $i;

How many times will the loop execute in both the cases.

Answers:

1. Infinite why?
We know that for loop has 3 blocks 1st is assignment 2nd is condition and 3rd is increment.

Now in first block we have assignment $i=1 We are fine with it
In second block we are having $i++ which means that it will check for value of $i as condition before incrementing so $i=1 and increment $i to 2 and again in next pass we have $i=2 which is again true value>0 results in true.
and it will go on until falls short of memory.

2. 0 Why?

$i=0 initially checked that condition before increment $i=0 which returns false and as such loop halts.


No comments:

Post a Comment