可以在循环中使用while循环吗?

Kei*_*gan 0 php while-loop

我要做的是以下内容:我有一个值数组,这些值最终将用于生成随机唯一字符串,但稍晚一点.首先,我想循环遍历数组中的所有值(foreach循环),然后我想限制它(while循环)这是一个正确的方法吗?

下面的代码不起作用,任何人都可以看到我做错了什么?

<?php 

    $array = array(
          '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 
          'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
          'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
          'u', 'v', 'w', 'x', 'y', 'z', '!', '£', '$', '%',
          '^', '&', '*', '(', ')', '_', '+', '{', '}'
    );

    $length_of_unique_key = 15;
    $counter = 0;

    foreach($array as $values)
    {
          $counter++;

          while ($counter <= $length_of_unique_key)
          {

          }
    }

?>
Run Code Online (Sandbox Code Playgroud)

bsn*_*eze 11

你不应该在while循环中递增你的计数器,所以它可以退出吗?


Cal*_*vin 7

查看循环(或任何其他控制结构)的错误的最佳方法就是运行它.有时你可以在头脑中做到这一点; 在其他时候,将跟踪点插入代码可能会有所帮助.

在这种情况下,我认为如果您只是简单地浏览一下代码中的代码,那么您将能够找到它的错误.但出于教学目的,我将在这里完成它.首先让我们为每行代码编号:

$array = array(...);               // line 1
$length = 15;                      // line 2
$counter = 0;                      // line 3
foreach($array as $values)         // line 4
{
      $counter++;                  // line 5
      while ($counter <= $length)  // line 6
      {
                                   // line 7
      }                            // line 8
                                   // line 9
}                                  // line 10
Run Code Online (Sandbox Code Playgroud)

现在让我们来看看它:

  1. $array 被赋予一个单维数组:
    array(0 => '1', 1 => '2', 2 => '3', ...)
  2. $length设置为15.
  3. $counter是设置0.
  4. 开始for loop; $values= $array[0]= '1'.
  5. $counter增加.$counter= 1.
  6. 开始while loop; 检查$counter(1)<= $length(15).
  7. 没做什么.
  8. 回到第6行.
  9. 第6行:如果$counter(1)<= $length(15),继续循环.
  10. 第7行:什么都不做.
  11. 第8行:回到第6行.
  12. 第6行:$counter(1)仍然<= $length(15),再次进入循环.
  13. 第7行:什么都不做.
  14. 第8行:回到第6行.

正如您所看到的,您陷入了无限循环,因为它既$counter不会$length改变值也不会改变.所以第while6行的条件总是计算为(1 <= 15).