【问题标题】:php - for loop inside a while loop, correct syntax?php - while 循环内的 for 循环,语法正确吗?
【发布时间】:2012-03-29 10:08:30
【问题描述】:

我有这个循环

while (count($arr) < 7)
        {

            $string = 'xx';
            for ($i=0; strlen($string) < 4; $i++)
            {
                $string = $string.'1';
            }
            echo "<br>array length is less than 7, word $string is created.";
            $arr[] = $string;
        }

每次我运行这部分代码时,我的 xampp 本地服务器都会超时并给出未找到服务器的错误。

我发现如果我删除内部for 循环,它会运行良好。把for循环放在while循环里面有什么问题吗?

另外,我在for 循环中的条件语句strlen($string) &lt; 4 没有对$i 变量的任何引用,但我没有看到任何不符合逻辑的条件语句与计数器无关。我错了,是否需要与计数器进行某种比较?

TIA

【问题讨论】:

  • 你从来不用$i,所以你可以改成while( strlen($string) &lt; 4)
  • 找不到服务器错误??这和php语法有什么关系?
  • 我认为这绝对没有问题..我会继续思考..
  • 乍一看,它看起来不错,与嵌套循环无关。我个人使用 NetBeans;你可能会选择 Eclipse、Zend 等。但是,如果你没有调试器来单步调试你的代码,你就不会走得太远。
  • 尼克,她以后可能想用它。它没有错,除非你怀疑它以某种方式导致错误。它可能导致错误的唯一方法是如果 $string 之前通过引用分配给它,我对此表示怀疑。 $string=&$i 会导致这样的错误...

标签: php for-loop while-loop


【解决方案1】:

在一段时间内有一个 for 没什么错。

你的“for”会更好一点,因为

while(strlen($string) < 4) {
    $string = $string.'1';
}

【讨论】:

  • 谢谢约翰,我有 $i 的原因是因为我使用 $i 作为数组索引,这部分代码被遗漏了。
  • 嗯,你的 PHP 是有效的,对我有用 - 问题一定出在其他地方(也许在你省略的某些代码中?)
  • 再次感谢,我正在浏览我很短的省略代码,看看是否还有其他内容。至少我知道错误不是由于循环造成的。
【解决方案2】:

我没有发现你的 php 有任何问题。

我完全复制了你的代码,根本没有无限循环。

我得到的结果如下:

<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.

我唯一的建议是改变:

$string = $string.'1';

$string .= '1';

【讨论】:

  • 感谢 Brian 测试代码,我编辑的代码用作示例,而不是真实代码。
猜你喜欢
  • 2019-11-10
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 2012-10-02
  • 2015-04-21
  • 2022-01-22
相关资源
最近更新 更多