-2

我有一个网站,我需要使用 while 语句,但是当我使用它时,它会无限重复回声。虽然看起来我可以在没有 while 的情况下让它工作,但事实并非如此,这是最终产品的简化版本,需要 while。

<?php 
$passlevel = '0';
while ($passlevel == '0')
{
    if(isset($_GET['box_1_color']))
    {
        $color=$_GET['box_1_color'];
        if($color == "#800080")
        {
            echo "you have passed step one.";
            $passlevel == '1';      
        }
        else 
        {
            echo "you didn't select purple.";
        }   
    }
    else echo "contact webmaster";
}
?>

为什么它与联系网站管理员或您没有无限次选择紫色相呼应?

4

5 回答 5

6

首先,您可能需要更改:

$passlevel == '1';

$passlevel = '1';

第一个是比较等于,而不是赋值等于。

其次,如果$coloris not #800080,则循环不会终止,因此会永远重复,因为循环中没有任何内容会导致值发生变化。

I'm not entirely sure of the point of this loop in the first place. It should work perfectly fine without the loop, however you've stated that your code is a simplified version of something more complicated that indeed needs a loop. Perhaps you can elaborate.

于 2012-07-08T02:58:38.013 回答
4

You're not providing any way out of the loop. If $_GET['box_1_color'] isn't purple the first time through the loop, it can't possibly become anything else the second time through the loop, so it'll keep being the wrong color each and every time.

I'm not certain what you intended for this loop to accomplish. If you're trying to have the user enter a new value each time, you won't be able to do that with a loop in PHP. You'll have to regenerate the entire page (with an error message, presumably) and ask the visitor to submit the form again.

于 2012-07-08T03:01:34.417 回答
1

In the case of "contact webmaster", you need to break out of the loop, either with the break expression or by setting your $passlevel to anything other than zero. A more serious real problem is revealed in @Mike Christensen's answer, though

于 2012-07-08T02:59:11.830 回答
1

If $_GET['box_1_color'] is not set, the variable $passlevel will never be changed.

于 2012-07-08T02:59:34.200 回答
-1
<?php 
$passlevel = 0;
while ($passlevel == 0 || $passlevel == 2)
{
    if(isset($_GET['box_1_color']))
    {
        $color=$_GET['box_1_color'];
        if($color == "#800080")
        {
            echo "you have passed step one.";
            $passlevel = 1;      
        }
        else 
        {
            echo "you didn't select purple.".'try again.';
        }   
    }
    else
    {
        echo "contact webmaster";
        $passlevel = 2;
    }
}
?>

You need to define another passlevel for failure, to stop the while loop. Also, don't put any quotes around integers.

于 2012-07-08T03:03:10.203 回答