php从变量中减去一个变量来获取值

时间:2015-04-01 15:10:47

标签: php variables random infinite-loop

我正在学习PHP而且我无法让这段代码工作,我刚开始进入php并且无法弄清楚这一点。在线验证器报告没有发现任何问题,但它为我设置了无限循环。有人可以告诉我为什么没有从$ eggs中减去$ eggsUsage。

谢谢:-)

<?php

    $eggs = 12;
    $eggUsage = 0;

    while($eggs - $eggUsage > 0) {
    $eggUsage = rand(0, 1, 2, 3, 4);
    $eggs = $eggs - $eggUsage;

    echo "You have {$eggs} left";
    }

    if ($eggs < 4) {
    $eggUsage = rand(0, 1, 2, 3, 4);
    $eggs == $eggs - $eggUsage;

    echo "You are almost out. BUY EGGS!";
    }

    echo "<p>Congratulations, you are out of eggs.</p>"  
?>

2 个答案:

答案 0 :(得分:0)

rand()需要2个参数,你在代码中给出了4个参数。 试试rand( 0, 4 )

另外,请勿忘记上一次回音中的;,并且$eggs == $eggs - $eggsUsage行中有一个错误,该错误应为=

此代码段对我来说非常合适:

    $eggs = 12;
    $eggUsage = 0;

    while($eggs - $eggUsage > 0) {
       $eggUsage = rand(0,4);
       $eggs = $eggs - $eggUsage;

       echo "You have {$eggs} left";
    }

    if ($eggs < 4) {
       $eggUsage = rand(0,4);
       $eggs = $eggs - $eggUsage;

       echo "You are almost out. BUY EGGS!";
    }

    echo "<p>Congratulations, you are out of eggs.</p>" ;

答案 1 :(得分:0)

从数组中选择值应为array_rand(0,1,2,3,4),但由于数组包含0到4之间的数字,rand(0,4)是正常的。