php检查数组值是否连续

时间:2012-01-01 21:19:24

标签: php arrays

我有一个数组$dice (4,7,3,6,7)

我需要一种检查该数组中每个值是否为连续数字的方法。

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:3)

试试这个:

$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

答案 1 :(得分:1)

function HasConsec($array)
{
    $res = false;
    $cb = false;
    foreach ($array as $im)
    {
        if ($cb !== false && $cb == $im)
            $res = true;
        $cb = $im + 1;
    }

    return $res;
}

答案 2 :(得分:1)

我认为这就是你要找的东西

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 />';
    }
}

答案 3 :(得分:0)

但是,我不是PHP开发人员,我知道这个问题看起来很老,但是我想与您分享一个简单的算法,它可以告诉您数组是否连续。

以下是步骤:

  • 查找输入数组的最大数量和最小数量。

  • 应用等式:$('#cashbill').change(function() { $('#bill_icon').toggleClass('hidden', $(this).val() === ''); });

  • 如果为true,则在其他情况下都是连续的false。