Aris
Aris

Reputation: 37

Is my second for loop able to iterate using the increment from my first loop?

What I want is the first loop iterating from 1 to 4 and the second loop from 5 to 6.

Here is my code:

<?php
for ($i = 1 ; $i <= 4 ; $i++)
{
    echo $i . "<br>";
}
?>
<hr>
<?php  
for ($i = 1 ; $i <= 2 ; $i++)
{
    echo $i . "<br>";
}
?>

Upvotes: 0

Views: 59

Answers (3)

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

Your problem

The second for loop resets your $i variable to 1:

for ($i = 1 ; $i <= 2 ; $i++)

Solution

You can use a while loop instead of your second for loop:

<?php
for ($i = 1; $i <= 4; $i++)
{
  echo $i . "<br>";
}
?>

<hr>

<?php
while ($i <= 6) // `<= 6` instead of `<= 2`, since we keep $1's value
{
  echo $i . "<br>";
  $i++;
}
?>

Upvotes: 1

iainn
iainn

Reputation: 17417

Rather than using two loops for this, why not just output the <hr> tag at the appropriate point within the same one? If you carry on with adding extra loops, first of all you'll run into confusing problems like this about (re-)initialising variables, and you'll also quickly end up with a lot of unnecessary duplicated code.

You can use the PHP modulo operator (%) to output the <hr> tag after every fourth element, which will both reduce the complexity and be a lot more extensible if you later add more elements:

for ($i=1; $i<=6; $i++) {
    echo $i . "<br>";

    if ($i % 4 === 0) {
        echo "<hr>";
    }
}

See https://eval.in/976102

Upvotes: -1

J K
J K

Reputation: 642

The loops you've given are:
1st loop: from 1 to 4
2nd loop: from 1 to 2

First loop is ok, but seconds needs to be modified. Use $i<=6 and don't initialize $i variable.
This will give you:

1st loop: from 1 to 4
2nd loop: from (value that 1st loop have ended)+1 to 6, so (4+1) to 6, 5 to 6

<?php
$i = 0; // be sure 'i' is visible in both loops
for ($i=1; $i<=4; $i++) // form 1 to 4
{
    echo $i . "<br>";
}
?>
<hr>
<?php  
$i++; // start from 5, not 4
for (; $i<=6; $i++) // from the previous value to 6
{
    echo $i . "<br>";
}
?>

Upvotes: 2

Related Questions