2014-09-25 88 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