在 PHP 中,我需要使用 for 循环来迭代用户指定的次数


In PHP, I need to use a for loop to iterate the number of times specified by the user

我正在做一个作业来复制一个页面,在该页面中,您将一个数字输入文本框,然后循环迭代该次数(在 0 到 5 之间)。IE,

输入: 5

输出: 迭代为 1.
迭代为 2.
迭代为 3.
迭代为 4.
迭代为 5.

我正在使用这个:

<?php
    $rows = $_GET['rows'];
    for ($rows = 1; $rows <= 5; $rows++) {
        echo "Iteration is $rows <br />";
    }
?>

我的表单看起来像这样:

<form action="" method="get">
   <p>Iterations:
       <input type="text" name="rows">
       <input type="submit" value="Loop">
   </p>
</form>

使用的代码只返回我输入的任何数字的列表 1-5。

您正在循环中重置变量。对于循环,您必须使用不同的变量,然后将最大限制设置为$rows变量。

<?php
   $rows = intval($_GET['rows']);   // Make sure its an integer
   for ( $i = 1; $i <= $rows; $i++ ) {
      echo "Iteration is $i <br />";
   }
?>

信用:在这个答案中强制$rows是一个整数是在@nurakantech从同一问题的答案中汲取灵感后完成的。

<?php
$rows = $_GET['rows'];
for($i = 1; $i <= (int)$rows; $i++){
   echo "Iteration $i.<br>";
}

试试这个:

for ($i = 1; $i <= $rows; $i++) {
    // $rows[$i] <-- This holds your $rows data
}

您正在覆盖循环中$rows的值。你需要做这样的事情:

<?php
$rows = $_GET['rows'];
for ($x = 0; $x < $rows; $x++) {
  echo "Iteration is $x <br />";
}
?>

在你的循环中使用另一个变量名,如:

 for ($i = 1; $i <= $rows; $i++){
   //manage stuff here
 }