php检查数组值是否连续

时间:2021-06-07 21:36:05

I have an array $dice (4,7,3,6,7)

数组$dice (4,7,3,6,7)

I need a way of checking if each of the values in that array are consecutive numbers.

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

Is there an easy method of doing this?

有简单的方法吗?

3 个解决方案

#1


3  

try this:

试试这个:

$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

#2


1  

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

    return $res;
}

#3


1  

I think this that this is what you are looking for

我想这就是你要找的

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

#1


3  

try this:

试试这个:

$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

#2


1  

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

    return $res;
}

#3


1  

I think this that this is what you are looking for

我想这就是你要找的

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