Understanding PHP for loop [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have a problem understanding how is the result 34 when it should be 32.Because the loop run's 4 times so when u add up 8 to the variable age it should bring up the sum as 32.Maybe I'm wrong please help out to understand.TQ
<?php
$age=24;
for($i=0; $i<=4; $i++){
$age= $age + 2;
}
echo ("At the end of the loop age = $age" );
?>
Result >>>>>>At the end of the loop age = 34

Your loop is not running four times; it's running five times.
$i<4 means the loop will terminate when $i reaches four - it terminates before that execution happens. $i<=4 means "continue looping so long as $i is less than or equal to four"
So, let's work through the examples:
for($i=0; $i<=4; $i++)
Begins, sets $i to value of 0
Loop: is $i less than or equal to 4? $i=0, so yes. $age += 2. ($age now equals 26).
End of first loop: $i++ ($i now equals 1).
Loop: is $i less than or equal to 4? $i = 1, so yes. $age += 2; ($age now equals 28).
End of second loop: $i++ ($i now equals 2).
Loop; is $i less than or equal to 4? $i = 2, so yes. $age += 2; ($age now equals 30).
End of third loop: $i++ ($i now equals 3).
Loop; is $i less than or equal to 4? $i = 3, so yes. $age += 2; ($age now equals 32).
End of fourth loop: $i++ ($i now equals 4).
Loop; is $i less than or equal to 4? $i = 4, so yes -- $i is equal to four, as specified by <=. $age += 2; ($age now equals 36).
End of fifth loop: $i++ ($i now equals 5).
Loop; is $i less than or equal to 4? $i = 5, so no. Loop terminates.
Final result: $age = 36

The number of elements between 0 and positive N is N+1.
You loop through 0 1 2 3 4.
Those are 5 iterations.
24 + (2*5) = 34.

the loop runs from i=0 to i=4
i age
0 26
1 28
2 30
3 32
4 34 ------>loop stops when i=5 since 5<=4 turns false
5
it should be
<?php
$age=24;
for($i=0; $i<4; $i++){
$age= $age + 2;
}
echo ("At the end of the loop age = $age" );
?>
the loop runs from i=0 to i=3
i age
0 26
1 28
2 30
3 32 ------>loop stops when i=4 since 4<4 turns false
4
5

Well that's because the loop starts from 0, so it runs 5 times (0,1,2,3,4).
Loop 1 (when value is 0): 24 + 2 = 26;
Loop 2 (when value is 1): 26 + 2 = 28;
Loop 3 (when value is 2): 28 + 2 = 30;
Loop 4 (when value is 3): 30 + 2 = 32;
Loop 5 (when value is 4): 32 + 2 = 34;
you can either start with 1 as:
for($i=1; $i<=4; $i++)
or make it < 4 instead of <= 4, as:
for($i=0; $i<4; $i++)

Related

PHP - Skip multiple for loop iterations

I have this piece of code that goes through an array where each position contains a line of previously pasted text. I want the for loop to skip 2 times the number of columns input by the user, once it reaches a line that contains the word "Total". I've searched around but all I found were answers for other languages. Can anybody enlighten me on this?
Code:
1 $j = -1;
2 $step = 1;
3 for($i = 0; $i < count($statisticsinput); $i++){
4 if(strpos($statisticsinput[$i], "Total") !== false){
5 $i += 2*$_POST['columno']; //Trying to make the counter skip the 2*col iterations but seems to have no effect
6 if($step !== 2){ //The word Total appears 2 times in the pasted text, the first time
7 $step++; //should keep the script going but not the second one
8 }else{
9 break;
10 }
11 continue; //After incrementing the counter 2*col, skip over the next steps and
12 } //go to the next loop. I expected it to jump 2*col loops (usually 22)
13 if($i % $_POST['columno'] == 0){
14 $j++;
15 }
16 $employees[$j][] = $statisticsinput[$i];
17 }
Many thanks.

How work this for loop code (logic)? PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I do not understand the logic of this code. If $ i <5 why not print 5 times * but throw out only one * in first row?
$n = 5;
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo ' * ';
}
echo '<br>';
}
for ($i = $n; $i >= 1; $i--) {
for ($j = 1; $j <= $i; $j++) {
echo ' * ';
}
echo '<br>';
}
The logic is very simple. Look at the first for loop. You have a for loop inside the for loop so as soon as your outer for loop begins, you're inner for loop will also be executed.
For eg,
[FIRST ITERATION] - Your outer for loop starts with $i = 1, so your inner for loop will consider the value of $i as 1 and the inner loop is executed because $j <= $i will be true. So only 1 * is printed.
[SECOND ITERATION] - Your outer for loop starts with $i = 2, so your inner for loop will consider the value of $i as 2 and the inner loop is executed twice because $j <= $i will be true both times as the conditions 1 <= 2 and 2 <= 2 will both return true. So 2 stars(*) are printed.
[THIRD ITERATION] - Your outer for loop starts with $i = 3, so your inner for loop will consider the value of $i as 3 and the inner loop is executed thrice because $j <= $i will be true all the three times as the conditions 1 <= 3, 2 <= 3 and 3 <= 3 will all return true. So 3 stars(*) are printed.
[FOURTH ITERATION] - Your outer for loop starts with $i = 4, so your inner for loop will consider the value of $i as 4 and the inner loop is executed four times because $j <= $i will be true all the four times as the conditions 1 <= 4, 2 <= 4, 3 <= 4 and 4 <= 4 will all return true. So 4 stars(*) are printed.
[FIFTH ITERATION] - Your outer for loop starts with $i = 5, so your inner for loop will consider the value of $i as 5 and the inner loop is executed five times because $j <= $i will be true all the five times as the conditions 1 <= 5, 2 <= 5, 3 <= 5, 4 <= 5 and 5 <= 5 will all return true. So 5 stars(*) are printed.
SECOND OUTER FOR LOOP LOGIC:
[FIRST ITERATION] - Your outer for loop starts with $i = 5, so your inner for loop will consider the value of $i as 5 and the inner loop is executed five times because $j <= $i will be true all the five times as the conditions 1 <= 5, 2 <= 5, 3 <= 5, 4 <= 5 and 5 <= 5 will all return true. So 5 stars(*) are printed.
[SECOND ITERATION] - Your outer for loop starts with $i = 4, so your inner for loop will consider the value of $i as 4 and the inner loop is executed four times because $j <= $i will be true all the four times as the conditions 1 <= 4, 2 <= 4, 3 <= 4 and 4 <= 4 will all return true. So 4 stars(*) are printed.
[THIRD ITERATION] - Your outer for loop starts with $i = 3, so your inner for loop will consider the value of $i as 3 and the inner loop is executed thrice because $j <= $i will be true all the three times as the conditions 1 <= 3, 2 <= 3 and 3 <= 3 will all return true. So 3 stars(*) are printed.
[FOURTH ITERATION] - Your outer for loop starts with $i = 2, so your inner for loop will consider the value of $i as 2 and the inner loop is executed twice because $j <= $i will be true both times as the conditions 1 <= 2 and 2 <= 2 will both return true. So 2 stars(*) are printed.
[FIFTH ITERATION] - Your outer for loop starts with $i = 5, so your inner for loop will consider the value of $i as 5 and the inner loop is executed because $j <= $i will be true. So only 1 * is printed.
Remember that your second outer for loop is not incrementing but it is decremented by one each time you loop is executed. So it starts with 5 and ends with 1.
You start with a main counter $i that runs for each row. It starts at 1 and will stop when it reaches 5 (included) so you will get 5 lines.
Inside that loop you have a star counter $j that starts at 1 and stops when it reaches $i's value (included). So here are the iterations it does :
When $i == 1 :
Iteration 1: $j == 1 : it prints *
$j == $i : the loop stops and prints <br />
When $i == 2 :
Iteration 1: $j == 1 : it prints *
Iteration 2: $j == 2 : it prints *
$j == $i : the loop stops and prints <br />
When $i == 3 :
Iteration 1: $j == 1 : it prints *
Iteration 2: $j == 2 : it prints *
Iteration 3: $j == 3 : it prints *
$j == $i : the loop stops and prints <br />
... And so on until $i == 5 and the loop prints 5 stars before printing <br />
Then you have a second loop where $i starts at 5 and goes down to 1 included (so it will run 5 times) and the inner loop is the same as the first one so it will print as many stars as the value of $i per line. The successive values of $i are 5, 4, 3, 2 then 1 so your script prints 5 stars then 4 then 3 then 2 then 1.
Result :
The code you posted prints the following :
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
Just as expected.
If that's not what you expected of your script, please describe the expected behaviour so we can tell you what part should change.

How does for loop works actually in php?

I'm a newbie to php and I've understood all other loops in php but the question is I cannot understand how the for loops works for ex:
Here is the code;
$a = 0;
$b = 0;
for ($i=0; $i < 5; $i++) {
$a += 10;
$b += 5;
}
echo("At the end of the loop a=$a and b=$b");
When I execute this script the value of a = 50 and b = 25!
Is it multiplying the a value with i's increment value? like 10 * 5 = 50.
You start with $i=0, then you do $a+10 and $b+5 as long as $i <5
$i=0, $a=10, $b=5
$i=1, $a=20, $b=10
$i=2, $a=30, $b=15
$i=3, $a=40, $b=20
$i=4, $a=50, $b=25
$i=5, now the loop stops because $i is no longer <5
Your loop runs five times. Each time through the loop you add 10 to the value of $a. Doing that five times gives you 50.
This is the way it works.
Let's say you have a no dollars. And I tell you that I will give you a dollar everytime you do 5 chores. However, I will only give you 5 dollars. At first you have no dollars and after one chore I give you 5 dollars. Now you have 5 dollars. You do another chore and I give you another 5, bringing you to ten. I have now given you two dollars. I give you another 5 - you have 15. I give you another - 20 - and one more; bringing you to 25 dollars. Now I have given you my limit of dollars, and our loop is complete.
In this story, my dollars are your $i value. Beginning at 0, working up to 5. Your chores are your $b values, which are added to every time.
Code example:
for ($dollars=0; $dollars < 5; $dollars++) {
$chores += 5;
}
+= is not increment its an assignment operator.
http://php.net/manual/en/language.operators.assignment.php
As I mentioned in the comments, and others in their answers. += will add the value to on the right to the value on the left. so in a loop its like this
step 0 $a = 5 ( 0+5)
step 1 $a = 10 (5[previous iteration exit value]+5 )
step 2 $a = 15 (10[previous iteration exit value] + 5)
so on....
Of note is you can also do -= *= etc. and .=or append all the same kind of operation.
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ ) {
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
</body>
</html>
This will produce the following result −
At the end of the loop a = 50 and b = 25
For loop is entry condition loop. It evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet
The statements inside this for loop block will run 5 times, the value of $i will be 0 to 4;
Imagine the loops are running separately.
$a=0;
$b=0;
for ($i = 0; $i < 5; $i++){
echo $a += 10;
echo '<br>';
}
And the output like this.
10
20
30
40
50
Now another Loop
for ($i=0; $i < 5; $i++) {
echo $b += 5;
echo '<br>';
}
And the output like this
5
10
15
20
25
In each iteration it adds 10 and 5 to previous number of iteration using the assignment operator x += y.

For-loop mystery in PHP

Using PHP 5.6, why does this code outputs
2
5
8
11
instead of
3
6
9
?
for ($i = 0; $i < 10; $i++) {
echo $i += 2 . "<br />";
}
Because i starts at 0, not 1. Lets see what is happening:
Loop 1
Initiate i, i = 0;
Check for loop condition ($i < 10). i is 0 so yes, run the loop.
Add 2 to i and echo. 0 + 2 = 2, echo 2.
End of loop, add 1 to i. i is 3.
Loop 2
Check for loop condition ($i < 10). i is 3 so yes, run the loop.
Add 2 to i and echo. 3 + 2 = 5, echo 5.
End of loop, add 1 to i. i is 6.
And so on. So you add 2, echo out then add 1.
You may be expecting the i++ in the for loop to run before the code, but it runs at the end of the code. From the PHP website:
At the end of each iteration, expr3 is evaluated (executed).
If you want your output to be 3, 6, 9 then you would need to initiate i to 1 at the start of your loop.
for($i = 1; $i < 10; $i++)
The increment (i++) in the loop header happens after the loop body is executed. So, i is initialized to 0, then you add 2 and print it. Then, the loop header increments it to 3, then you add 2 and print it again...
In the first iteration, you add 0 + 2, because you declared $i to be 0, so the output would be 2. then with the $i++ you do the same as you would write $i += 1. So now the value of $i is 3.
Then you add again 2 which gives you 5 as an output, then you add another 1. Value of $i = 6, add 2... outputs 8... add 1... add 2... outputs 11...

how to do this.. backwards?

I currently have:
$i = 1;
while {
echo $i;
$i++;
}
And it shows:
1
2
3
4 etc..
How would I make it display backwards?
For example
4
3
2
1 etc..
I basically want to do the exact same thing but flip it around.
$i = 10;
while($i>0) {
echo $i;
$i--;
}
Example - Print number through 0 to 5 with PHP For Loop
for($i=0; $i<=5; $i=$i+1)
{
echo $i." ";
}
In the above example, we set a counter variable $i to 0. In the second statement of our for loop, we set the condition value to our counter variable $i to 5, i.e. the loop will execute until $i reaches 5. In the third statement, we set $i to increment by 1.
The above code will output numbers through 0 to 5 as 0 1 2 3 4 5.
Note: The third increment statement can be set to increment by any number. In our above example, we can set $i to increment by 2, i.e., $i=$i+2. In this case the code will produce 0 2 4.
Example - Print number through 5 to 0 with PHP For Loop
What if we want to go backwards, that is, print number though 0 to 5 in reverse order? We simple initialize the counter variable $i to 5, set its condition to 0 and decrement $i by 1.
for($i=5; $i>=0; $i=$i-1)
{
echo $i." ";
}
The above code will output number from 5 to 0 as 5 4 3 2 1 0 looping backwards.
Good luck! :)
If you want to back-word sr number as per your count of rows in result then use this.
$num_rows = mysqli_num_rows($query);
$x = $num_rows;
$x--;
$i = 4;
while($i > 0) {
echo $i--;
}

Categories