我要做的是以下内容:我有一个值数组,这些值最终将用于生成随机唯一字符串,但稍晚一点.首先,我想循环遍历数组中的所有值(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)
查看循环(或任何其他控制结构)的错误的最佳方法就是运行它.有时你可以在头脑中做到这一点; 在其他时候,将跟踪点插入代码可能会有所帮助.
在这种情况下,我认为如果您只是简单地浏览一下代码中的代码,那么您将能够找到它的错误.但出于教学目的,我将在这里完成它.首先让我们为每行代码编号:
$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)
现在让我们来看看它:
$array
被赋予一个单维数组:array(0 => '1', 1 => '2', 2 => '3', ...)
$length
设置为15.$counter
是设置0.for loop
; $values
= $array[0]
= '1'.$counter
增加.$counter
= 1.while loop
; 检查$counter
(1)<= $length
(15).$counter
(1)<= $length
(15),继续循环.$counter
(1)仍然<= $length
(15),再次进入循环.正如您所看到的,您陷入了无限循环,因为它既$counter
不会$length
改变值也不会改变.所以第while
6行的条件总是计算为真(1 <= 15).
归档时间: |
|
查看次数: |
2853 次 |
最近记录: |