简体   繁体   中英

add in loop in multi dimensional array

i am facing a problem can some one suggest me

for ($i = 1; $i <= 2; $i++) {
  $r2 = 0;
  for ($t = 1; $t <= 2; $t++) {
    echo $r2;
    $r2++
  }
}

output is 0101 ;

can i get output 0123 ??? please

if

for ($i = 1; $i <= 3; $i++) {
  $r2 = 0;
  for ($t = 1; $t <= 3; $t++) {
    echo $r2;
    $r2++
  }
}

output is 010101 ;

can output 012345678 ??? please

and if

 for ($i = 1; $i <= 4; $i++) {
   $r2 = 0;
   for ($t = 1; $t <= 4; $t++) {
     echo $r2;
     $r2++
   }
 }

output is 01010101 ;

can output 0123456789101112131415 ??? please i think you understand

thanks

In all of these cases you are initializing $r2=0; in the inner loop. It should be outside the loop.

$r2=0;
for($i=1;$i<=2;$i++){
  for($t=1;$t<=2;$t++){
    echo $r2;
    $r2++
  }
}

This would produce "1234".

why are you using two nested for loops ? why not just use one:

for ($i=0; $i<=15; $i++) echo $i . " ";

Try this:

$r2 = 10;
for($t = 0; $t <= $r2; $t++){
   echo $r2;
}

Oh wait.. I get it now, why you have the two nested loops, you want to essentially raise a number to the power of 2 in order to control the number of values output. In that case, what you want is simply this:

// this is the variable you need to change to affect the number of values outputed
$n = 2;

// Square $n
$m = $n * $n;

// Loop $m times
for ($i = 0; $i < $m; $i++) {
  echo $i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM