PhP通过for循环传递变量

时间:2013-10-11 00:49:20

标签: php for-loop counter

任何人都可以帮助我了解如何通过for循环传递变量吗?我想打印出变量$ guess,直到数字40&打印出“你猜到低”或“你猜得太高”......如何将变量与计数器连接?

$Me=30;
$guess=$i;

for ($i = 0; $i < 40; $i++) {
    if($Me>$guess){
    print "$guess:you guessed too low<br />";
    }elseif($Me<$guess){
    print "$guess: you guessed to high<br />";
    }else{
    print "you guessed my age! i'm 31!";
    }
}

4 个答案:

答案 0 :(得分:1)

$Me=30;

for ($i = 0; $i < 40; $i++) {
$guess=$i; // move it here
    if($Me>$guess){
    print "$guess:you guessed too low<br />";
    }elseif($Me<$guess){
    print "$guess: you guessed to high<br />";
    }else{
    print "you guessed my age! i'm 31!";
    }
}

答案 1 :(得分:1)

在for循环中用$ guess替换$ i。

然而,程序将打印“我是31”,尽管$ Me = 30。

答案 2 :(得分:1)

$Me=30;
/* actually you don't need to use $guess=$i; for your needs */ 
for($i = 0; $i < 40; $i++) {
    if($i < $Me){
        echo "$i:you guessed too low <br/>";
    }
    else if($i > $Me){
        echo "$i: you guessed to high<br/>";
    }
    else{
        echo "you guessed my age! i'm 31!";
    }
}

答案 3 :(得分:1)

$Me=30;

for ($i = 0; $i < 40; ) {
     $guess=$i;
    if($Me>$guess){
        print "$guess:you guessed too low<br />";
    }elseif($Me<$guess){
        print "$guess: you guessed to high<br />";
    }else{
        print "you guessed my age! i'm 31!";
    }
$i++;
}