Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php check if array values are consecutive

Tags:

arrays

php

I have an array $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?

like image 200
user1022585 Avatar asked Sep 25 '26 04:09

user1022585


1 Answers

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
like image 183
Ignas Avatar answered Sep 26 '26 18:09

Ignas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!