2015-09-26 108 views
0

下面是我的一些代碼部分:檢查多個字符串的spesific數

<?php 
       $terning1 = rand(1,6); 
       $terning2 = rand(1,6); 
       $terning3 = rand(1,6); 
       $terning4 = rand(1,6); 
       $terning5 = rand(1,6); 
       $terning6 = rand(1,6); 
//Here i need a system to check how many of them that gets number 6 
?> 

洙我需要的是方法來檢查多少$ terning1-6返回數量6可以說$ terning1和$ terning4然後我需要一種方式告訴我,他們中的2人是6.我不知道我怎麼能做到這一點,因爲我從來沒有做過這樣的事情。

回答

0

,如果你可以在一個陣列$terning

然後,

if (in_array(6,$terning)) { 
    //Do Something 
} 
+0

很抱歉,但我不知道如何保存所有那些在一個數組中,並且客棧這個代碼我怎麼得到有多少個6是?像$ howmany = SOMETHING; //應該給我的數量是6 –

1

存儲一切因爲你的方式已經命名的變量,你可以使用variable variables遍歷它們:

$sixes = 0; 
for ($i = 1; $i <= 6; $i++) { 
    $variable = "terning$i"; 
    if ($$variable === 6) { 
     $sixes++; 
    } 
} 

但我會強烈建議使用數組來代替你的數字,並在你去時計數六個數字:

$terning = array(); 
$sixes = 0; 
for($i = 1; $i <= 6; $i++){ 
    $terning[$i] = rand(1, 6); 
    if ($terning[$i] === 6) 
    { 
     $sixes++; 
    } 
} 

還是要算算賬他們:

$sixes = count(array_keys($terning, 6));

0

您可以使用array_count_values功能terning數值數組這樣的:

// Variable to determine the amount of randomly generated numbers 
    $amountOfTernings = 6; 

    $terningsArray = []; 

    // Storing the random numbers in an array 
    for($i = 0; $i < $amountOfTernings; $i++) { 
     $terningsArray[] = rand(1, 6); 
    } 

    // Constructs an array that counts the number of times a number has occurred 
    $terningOccurrences = array_count_values($terningsArray); 

    // Variable that stores the number of occurrences of 6 
    $howManySixes = isset($terningOccurrences[6]) ? $terningOccurrences[6] : 0; 
+0

我如何使用回聲來告訴數字? –

+0

echo $ howManySixes; –