I need to find out who’s sequence and who’s not, but my logic doesn’t work

Asked

Viewed 66 times

-1

<?php 

$a = array(1,2,5,8,9,10,12);
$length = count($a);

for ($i=0; $i < $length ; $i++) { 
    if (($a[$i+1]-$a[$i]) == 1) {

        echo " " .$a[$i]." é sucessor";

    }else{
        echo " " .$a[$i]." não faz parte da sequencia";

    }
}

?
  • When does $a[$i+1] in the last iteration(i$ === $length) an error is generated.

2 answers

4


You can do it this way

$a = array(1,2,5,8,9,10,11,12);
$length = count($a);

echo $a[0];
for ($i=1; $i < $length ; $i++) { 
    if ($a[$i-1] != $a[$i] - 1) {
      echo "<br>" .$a[$i]." Saiu da sequencia";
    }else{
      echo "<br>" . $a[$i];
    }
}

This way it shows the sequence and indicates when a number leaves the sequence, see the result

1
2
5 Saiu da sequencia
8 Saiu da sequencia
9
10
11
12
  • thank you so much... I didn’t think to do it backwards

1

Provided that the first element is no successor to anyone:

<?php 

$a = array(1,2,5,8,9,10,12);
$length = count($a);

for ($i=0; $i < $length -1; $i++) { 
    if (($a[$i+1]-$a[$i]) == 1) {

        echo " " .$a[$i+1]." é sucessor" ;
    }else{
        echo " " .$a[$i+1]." não faz parte da sequencia";
    }
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.