Harinarayan
Harinarayan

Reputation: 121

Running for loop inside other for loop

Can anyone help me understand why a variable takes its initial value after incrementing the variable? below is code:

$k= 0;
$l= 3;
for($i = 0; $i<3; $i++){
    for($j = $k; $j<$l; $j++){
        echo $j;
    }
    echo $k+3;
    echo $l+3;
}

In this we have two for loops running one inside other. Here we run three times the outside for loop, inside this we are running other for loop again. The problem we are facing is that when inner for loop end we have incremented $k and $l both by 3 but it always take value 0 and 3 respectively.

Upvotes: 1

Views: 83

Answers (6)

lazyCoder
lazyCoder

Reputation: 2561

@Harinarayan First of all you need to read about echo() http://php.net/manual/en/function.echo.php

echo — Output one or more strings

echo does not manipulate expression as you did in your question like:

echo $k+3;

instead of using echo for the increment you should first increment the variable and then echo that variable like below:

<?php
  $k= 0;
  $l= 3;
  for($i = 0; $i<3; $i++){
      for($j = $k; $j<$l; $j++){
          echo $j;
      }
      $k += 3;
      $l += 3;
      echo $k;
      echo "<br>";
      echo $l;
  }

Upvotes: 0

Abi
Abi

Reputation: 734

Try This

$k= 0;
$l= 3;
for($i = 0; $i<3; $i++){
    for($j = $k; $j<$l; $j++){
        echo $j;
    }
    $k = $k+3;
    $l = $l+3;
}
echo $k.'<br>';
echo $l;

First Increment the value and store it in the variable

$k = $k+3;
$l = $l+3;

Then You need to print using

echo $k.'<br>';
echo $l;

Upvotes: 0

chigs
chigs

Reputation: 194

TRY this.
$k += 3;
$l += 3;

echo $k;
echo $l;

Upvotes: 0

Christopher Smit
Christopher Smit

Reputation: 959

Try this:

    <?php
$k= 0;
$l= 3;
for($i = 0; $i<3; $i++){
    for($j = $k; $j<$l; $j++){
        $j = $j++;
    }
    $k = $k+3;
    $l = $l+3;
}

echo $k.'<br>';
echo $l;
?>

Gives you:

9 12

Upvotes: 0

Hugo G
Hugo G

Reputation: 16494

we have incremented $k and $l both by 3

Nope, you only print the result of your values plus 3, but you do not set them anywhere in the loop:

Instead of

echo $k+3;  
echo $l+3;

write

$k = $k + 3;
$l = $l + 3;

Upvotes: 2

Mabecr
Mabecr

Reputation: 34

You should try removing the "echo" and incrementing the variable in each loop. Then print them out after.

Upvotes: 0

Related Questions