2014-09-25 42 views
-1

我有5个变量产生一个随机数和第六个变量,这是用户输入。 然后我检查用户输入的$ userNum是否与任何随机数匹配。我知道这是一个愚蠢的游戏,但我只是搞乱了解更多PHPPHP比较用户输入与多个变量

必须有一个更简单的方法来做到这一点。

if(isset($_POST['submit'])) 
{ 
$userNum = $_POST['userNum']; 
$spot1 = rand(1, 100); 
$spot2 = rand(1, 100); 
$spot3 = rand(1, 100); 
$spot4 = rand(1, 100); 
$spot5 = rand(1, 100); 
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5; 
if($userNum == $spot1) 
    { 
    echo "you hit a mine!"; 
    exit(); 
} 
if($userNum == $spot2) 
    { 
    echo "you hit a mine!"; 
    exit(); 
} 
if($userNum == $spot3) 
    { 
    echo "you hit a mine!"; 
    exit(); 
} 
if($userNum == $spot4) 
    { 
    echo "you hit a mine!"; 
    exit(); 
} 
if($userNum == $spot5) 
    { 
    echo "you hit a mine!"; 
    exit(); 
} else { 
echo "you lived!"; 
} 
} 

回答

1

您不需要在数组或类似的东西中存储点,只需使用一个简单的循环即可。

<?php 

if(isset($_POST['submit'])){ 

    $userNum = (int) $_POST['userNum']; 
    $hitMine = false; 

    for($i = 1; $i <= 5; $i++){ 
     $randNum = rand(1, 100); 
     echo $randNum . '<br />'; 
     if($randNum == $userNum){ 
      $hitMine = true;  
     } 
    } 

    if($hitMine == true){ 
     echo "you hit a mine!"; 
    } 

} 

?> 
+1

非常感谢,我可以增加$ i <= 50个变量,节省大量时间。谢谢! – m1xolyd1an 2014-09-25 19:08:56

1

您可以使用Switch Case代替其他方法使其更好更快。

if(isset($_POST['submit'])) 
{ 
$userNum = $_POST['userNum']; 
$spot1 = rand(1, 100); 
$spot2 = rand(1, 100); 
$spot3 = rand(1, 100); 
$spot4 = rand(1, 100); 
$spot5 = rand(1, 100); 
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5; 
Switch($userNum) 
{ 
Case $spot1: 
Case $spot2: 
Case $spot3: 
Case $spot4: 
Case $spot5: 
     echo "you hit a mine!"; 
     break; 
default: echo "you lived!"; 
     break; 
} 

}

0

只是存储在数组中的有效点。

$myhashmap = array(); 
$myhashmap['spot1'] = true; 
$myhashmap['spot2'] = true; 

if(isset($myhashmap[$userNum])) 
    { 
    echo "you hit a mine!"; 
    exit(); 
} 

这里有一个关于PHP数组链接的详细信息:http://www.tutorialspoint.com/php/php_arrays.htm

1

我会做点阵列

$spot1 = rand(1, 100); 
$spot2 = rand(1, 100); 
$spot3 = rand(1, 100); 
$spot4 = rand(1, 100); 
$spot5 = rand(1, 100); 

// Make an array of the spots. 
$spots = array($spot1, $spot2, $spot3, $spot4, $spot5); 

if(in_array($userNum, $spots)) { 
    echo "you hit a mine!"; 
    exit(); 
} else { 
    echo "you lived!"; 
} 

50点以上的部位,你可以dynamicaly在插入值数组假设您在真实php代码中使用rand()函数:

$spots = Array(); 
for ($i = 0; $i < 50; $i ++) { 
    array_push($spots, rand(1,100)); 
} 

或:

for ($i = 0; $i < 50; $i ++) { 
    $spots[$i] = rand(1,100); 
} 
+0

谢谢,但如果我想要50 +点,我必须为每个创建一个数组和变量? – m1xolyd1an 2014-09-25 19:09:48

+0

@ m1xolyd1an我刚更新了我的答案。 – 2014-09-25 19:13:34