'php check if array values are consecutive
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?
Solution 1:[1]
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
Solution 2:[2]
function HasConsec($array)
{
$res = false;
$cb = false;
foreach ($array as $im)
{
if ($cb !== false && $cb == $im)
$res = true;
$cb = $im + 1;
}
return $res;
}
Solution 3:[3]
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 />';
}
}
Solution 4:[4]
However, I'm not a PHP developer and I know that the question looks very old but there is an easy algorithm which I like to share with you that can tell you if your array is consecutive or not.
Here are the steps:
find the maximum number and the minimum number of the input array.
apply the equation:
(max - min + 1) == array.length.if true, then it is consecutive other wise false.
Solution 5:[5]
I came up with another approach:
$nums = [-1,0,1];
$nums = array_unique($nums); # optional, comment on the bottom
$range = range(min($nums), max($nums));
$diff = array_diff($range, $nums);
$isConsecutive = empty($diff) && count($nums) === count($range);
$nums = array_unique($nums) - add this if you consider arrays with duplicated numbers valid too e.g. [-1,0,1,1]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ignas |
| Solution 2 | craig1231 |
| Solution 3 | GuZzie |
| Solution 4 | |
| Solution 5 | micper |
