Error comparing array php

1
$rua[] = {1,1,2,2,2,2};

$countRua = count($rua, COUNT_RECURSIVE);

for ($i=0; $i < $countRua; $i++) { 
    if ($rua[$i] == $rua[$i+1]) {

    }
}

I have for above traversing a array and validating if the position is equal to the next position, but when it arrives in the last it tries to compare with position 7 and returns the error below, some way to adjust it?

  

Undefined offset: 6

    
asked by anonymous 15.03.2018 / 14:53

2 answers

0

You can solve this by checking if the index exists with isset() the if condition should be composed like this:

if (isset($rua[$i+1]) && $rua[$i] == $rua[$i+1]) {
    
15.03.2018 / 15:09
1

Better start of second item and every loop compare with previous:

$rua[] = {1,1,2,2,2,2};

$countRua = count($rua, COUNT_RECURSIVE);

for ($i=1; $i < $countRua; $i++) { 
    if ($rua[$i] == $rua[$i-1]) {

    }
}
    
15.03.2018 / 14:56