For-loop mystery in PHP - 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...

Related

(PHP) Why does this generator-script adds the starting value + the step-value to the starting value?

the title may be pretty confusing. Here's a script which requires a start-end and step value to add numbers to the start value:
function addieren($start, $ende, $schritt = 1) {
if ($start < $ende) {
$erg = 0;
for ($i = $start; $i <= $ende; $i += $schritt) {
$erg += $i;
yield $erg;
}
}
}
foreach (addieren(2, 10, 2) as $erg) {
echo $erg . "<br>";
}
So the start value is 2, the end value is 10 (but it's not ending at 10 as the result shows), and it should add 2 to the $i every step.
Here's the output:
2
6
12
20
30
The first output is clear to me, since the $erg was 0 and it added the 2 because of 2 steps.
But the next output is 6 and I don't get why. In the second loop, $i is 2 and and the script says: $i += $schritt so when $i is 2 and the $schritt value is also 2, why doesn't that output 4 as the second output? Hope you get what I mean.. I guess it's a pure logic error in my head.

Understanding PHP for loop [closed]

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++)

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.

While loop ommitting every fourth result

I'm try to dynamically generate an HTML table containing data from a database. The output looks perfect, but upon closer inspection I realized it was omitting every fourth result. I know it has something to do with the structure of my while loop and the if/else statement within, but I'm not sure what it is exactly.
$i=0;
while ($person = $pull_person->fetch()){
if ($i <= 2){
echo "<td valign='top'>";
echo "<h3>" . $person['person_name'] . " - " . $person['person_id'] . "</h3>";
echo "<label style='background-image:url(" . $person['person_pic'] . ");'><input type='checkbox' name='person[]' value='" . $person['person_id'] . "''></label>";
echo "</td>";
$i++;
}
else{
echo "</tr>";
echo "<tr>";
$i=0;
}
}
It's gotta be something simple/obvious, but it's not registering with me. Thanks!
The loop is not hitting the fourth result because of the loop limiting logic.
$i=0;
while ($person = $pull_person->fetch()){
if ($i <= 2){
echo "<p>item: $i</p>";
$i++;
}
}
Iteration 1: $i = 0
Iteration 2: $i = 1
Iteration 3: $i = 2
Iteration 4: $i = 3
Iteration 4 is never hit because it checks and sees that $i must be less than or equal to 2. If you change this to be less than or equal to 3 it will work as you want.
if ($i <= 3)
Evidently... you only increment the variable $i when the condition is met:
$i=0;
while ($person = $pull_person->fetch())
{
if ($i <= 2)
{
//output
$i++;
}
else
{
//no output
$i=0;
}
}
So this happens:
iteration old $i new $i output
1 0 1 yes
2 1 2 yes
3 2 3 yes
4 3 0 no //condition not met
5 0 1 yes //loops...
...
What you observe here is that the code will skip the output of the iteration given by the number in the conditional plust 2. So, for example, if you use the condtion $i <= 3, the results are:
iteration old $i new $i output
1 0 1 yes
2 1 2 yes
3 2 3 yes
4 3 4 yes
5 4 0 no //condition not met
6 0 1 yes //loops...
...
If you want to insert something each n iterations, do as follows:
$n = 3; //number of items per row
$i = 0;
while ($person = $pull_person->fetch())
{
//output item
$i++;
if ($i == $n)
{
//something each $n iterations
$i=0;
}
}
The effect is the following (assuming $n = 3):
iteration old $i new $i new row
1 0 1 no
2 1 2 no
3 2 0 yes //condition is met, $i reset to 0
4 0 1 no
5 1 2 no
6 2 0 yes //condition is met, $i reset to 0
...
Note 1: every iteration outputs an item.
Note 2: you can adjust the initial value of i to have an offset.
Misread question but will leave the answer as it may provide use anyway.
Best way is to look at the array as a 'module' (mathematically) -- i.e. use Modular Arithmetic:
if ((i % 4) == 0)
That is to say, indices 0, 4, 8, 12, 16, ... will be targeted, only. And, actually, this is how most setInterval functions work under the hood.

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