2015-09-26 80 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; –