我有一个数组$dice (4,7,3,6,7)
我需要一种方法来检查该数组中的每个值是否都是连续的数字。
有没有一种简单的方法可以做到这一点?
发布于 2012-01-02 05:31:49
试试这个:
$dice = array(4,5,2,6,7);
function checkConsec($d) {
for($i=0;$i<count($d);$i++) {
if(isset($d[$i+1]) && $d[$i]+1 != $d[$i+1]) {
return false;
}
}
return true;
}
var_dump(checkConsec($dice)); //returns false
var_dump(checkConsec(array(4,5,6,7))); //returns true发布于 2012-01-02 05:24:34
function HasConsec($array)
{
$res = false;
$cb = false;
foreach ($array as $im)
{
if ($cb !== false && $cb == $im)
$res = true;
$cb = $im + 1;
}
return $res;
}发布于 2012-01-02 05:39:44
我想这就是你要找的东西
for ($c = 0; $c < count($dice); $c++){
$next_arr_pos = $c+1;
if ($c == (count($dice) -1)){
$cons_check = $dice[$c];
}
else
{
$cons_check = $dice[$next_arr_pos];
$gap_calc = $cons_check-$dice[$c];
}
if ($dice[$c] < $cons_check && $gap_calc == 1){
echo 'arr_pos = '.$dice[$c].' Is consecutive with '.$cons_check.' <br />';
}
}https://stackoverflow.com/questions/8695620
复制相似问题